����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 : 54.89.25.11  /  Your IP : 216.73.216.121
Web Server : Apache/2.4.7 (Ubuntu)
System : Linux ip-172-31-88-18 3.13.0-74-generic #118-Ubuntu SMP Thu Dec 17 22:52:10 UTC 2015 x86_64
User : www-data ( 33)
PHP Version : 5.5.9-1ubuntu4.24
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/kalemon/module-old/Secure/src/Secure/Controller/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/kalemon/module-old/Secure/src/Secure/Controller//GradeController.php
<?php

namespace Secure\Controller;

use Zend\Form\FormInterface;
use Zend\Db\TableGateway\TableGateway;
use Secure\Model\UserManagement\UserManagementTable;
use Secure\Model\Grade\AddClassInputFilter;
use Secure\Form\Grade\AddClassForm;
use Secure\Model\Grade\AddBatchInputFilter;
use Secure\Form\Grade\AddBatchForm;
use Secure\Model\Grade\AddGradeInputFilter;
use Secure\Form\Grade\AddGradeForm;
use Secure\Model\Grade\AddSyllabusInputFilter;
use Secure\Form\Grade\AddSyllabusForm;
use Secure\Form\Grade\AddLessonPlanForm;
use Secure\Model\Grade\AddLessonPlanInputFilter;
use Secure\Model\Grade\GradeTable;
use Secure\Model\SchoolBook\BookTable;
use Secure\Model\Curriculum\CurriculumTable;
use Secure\Model\Administrator\AdministratorTable;
use Zend\View\Model\JsonModel;
use Zend\Session\Container;
use Zend\Http\Client as HttpClient;
use Zend\Http\Request;
//Load LP add content form
use Secure\Form\Grade\AddAssignmentForm;
use Secure\Model\Grade\AddAssignmentInputFilter;
use Secure\Form\Grade\AddLiveClassForm;
use Secure\Model\Grade\AddLiveClassInputFilter;
use Secure\Form\Grade\AddLpTextForm;
use Secure\Model\Grade\AddLpTextInputFilter;
use Secure\Form\Grade\AddLpLinkForm;
use Secure\Model\Grade\AddLpLinkInputFilter;
use Secure\Form\Grade\AddLpEmbedForm;
use Secure\Model\Grade\AddLpEmbedInputFilter;
use Secure\Model\Grade\AddLpImageInputFilter;
use Secure\Form\Grade\AddLpImageForm;
use Secure\Model\Grade\AddLpVideoInputFilter;
use Secure\Form\Grade\AddLpVideoForm;
use Secure\Model\Grade\AddLpAudioInputFilter;
use Secure\Form\Grade\AddLpAudioForm;
use Secure\Model\Grade\AddLpWidgetInputFilter;
use Secure\Form\Grade\AddLpWidgetForm;
use Secure\Model\Grade\AddLpDocumentInputFilter;
use Secure\Form\Grade\AddLpDocumentForm;
use Secure\Form\Grade\AddLpQuizForm;
use Secure\Model\Grade\AddLpQuizInputFilter;
use Zend\Validator\File\Size;
use ZipArchive;
use Secure\Model\Grade\SubjectInputFilter;
use Secure\Form\Grade\SubjectForm;
use Checkondispatch\Custom\AbstractSecureController;
use Aws\Sdk;
use ScormEngineUtilities;
use ScormEngineService;
use ReportingService;
use Configuration;
use GetReportageAuth;
use Checkondispatch\Custom\WizIqApi;
use Secure\View\Helper\WiziqHelper;
use Secure\Controller\Plugin\EmailPlugin;
use Zend\View\Model\ViewModel;

//use Checkondispatch\scorm\ScormEngineUtilities;
class GradeController extends AbstractSecureController {

    //initialize Table object for CRUD
    function initModelObject() {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $this->db = new GradeTable($dbadapter);
    }

    //get service helper
    function getHelperMgr() {
        return $this->getServiceLocator()->get('ViewHelperManager');
    }

    //get adapter
    function getAdapter() {
        return $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
    }

    function sketchAction() {
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        return $viewModel;
    }
       
    /**
     * @desc This is an default action if not defined then redirect to its user specific route.
     * @created by SAIF <shakeel.saif@veative.com>
     * @created on 02.02.18
     * @return ViewModel
     */
    public function indexAction() {
        return $this->getEvent()->getRouteMatch()->setParam('action', 'index-not-found');
    }

    //list all grades by Batch ID
    public function listGradeAction() {
        //print_r($this->container->language); die;
        $batchId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $this->db = new GradeTable($dbadapter);
        $grades = $this->db->getGrades($batchId);
        $batchDetail = $this->db->getBatchDetails($batchId, $this->container->authDetail['ORG_ID']);
        if (empty($batchDetail)) {
            return $this->redirect()->toRoute('grade', array('action' => 'list-batch'));
        }
        $viewModel->setVariables(['grades' => $grades, 'batchDetail' => $batchDetail]);
        return $viewModel;
    }

    public function addGradeAction() {
        $batchId = $this->params('id');
        if (empty($batchId)) {
            return $this->redirect()->toRoute('grade');
        }
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $result = ['result' => false, 'message' => ''];
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $addGradeForm = new AddGradeForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
        // Ajax request to save data
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $register = new AddGradeInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addGradeForm->setInputFilter($register->getInputFilter());
            $addGradeForm->setData($request->getPost());
            if ($addGradeForm->isValid()) {
                $postData = $request->getPost()->toArray();
                $postData['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                $postData['BATCH_ID'] = $batchId;
                $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
                $this->db = new GradeTable($dbadapter);
                $grades = $this->db->addSyllabus($postData);
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-grade/' . $batchId;
                    $result = ['result' => true, 'message' => 'Grade has been added successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addGradeForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['form' => $addGradeForm, 'data' => $result, 'batchId' => $batchId]);
        return $viewModel;
    }

    //to update school grade
    public function editGradeAction() {
        $gradeId = $this->params('id');
        if (empty($gradeId)) {
            return $this->redirect()->toRoute('grade');
        }
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $result = ['result' => false, 'message' => ''];
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $addCourseForm = new AddGradeForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $this->db = new GradeTable($dbadapter);
        $gradeDetails = $this->db->getGradeDetails($gradeId);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $register = new AddGradeInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addCourseForm->setInputFilter($register->getInputFilter());
            $addCourseForm->setData($request->getPost());
            if ($addCourseForm->isValid()) {
                $postData = $request->getPost()->toArray();
                $grades = $this->db->updateGrade($postData, $gradeId);
                $batchId = $gradeDetails['BATCH_ID'];
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-grade/' . $batchId;
                    $result = ['result' => true, 'message' => 'Grade has been updated successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addCourseForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['form' => $addCourseForm, 'gradeDetails' => $gradeDetails, 'data' => $result, 'gradeId' => $gradeId]);
        return $viewModel;
    }

    //add module
    function saveSyllabusLpAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $addForm = new AddSyllabusForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $postData['grade_batch_id'], $postData['parentCat']);
            $catgFilter = new AddSyllabusInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($catgFilter->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $this->initModelObject();
                if (!isset($postData['position'])) {
                    //update syllabus
                    $result = $this->db->updateCategory($postData);
                } else {
                    //insert syllabus
                    $result = $this->db->insertNewCategory($postData);
                }
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-module/' . $postData['grade_batch_id'];
                    $result = ['result' => true, 'message' => 'User has been invite successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    public function getLoByTopicAction() {

        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postData = $request->getPost()->toArray();
            //  $table = $this->initTable('MasterTopic\Model\MasterTopicTable');
            $this->db = new GradeTable($dbadapter);
            $topic_id = $postData['topic_id'];
            $loData = $this->db->getLoByTopicId($topic_id);
            $loOption = array();
            foreach ($loData as $data) {
                $loOption[$data['TOPIC_ID'] . "_" . $data['LO_ID']] = $data['LO_NAME'];
            }
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $loOption
            ));
            return $jsonModel;
        }
    }

    public function getLoByTopicselectedAction() {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $request = $this->getRequest();
        $option = '';
        $count = 0;
        if ($request->isXmlHttpRequest()) {
            $postData = $request->getPost()->toArray();
            //  $table = $this->initTable('MasterTopic\Model\MasterTopicTable');
            $this->db = new GradeTable($dbadapter);
            $topic_id = $postData['topic_id'];
            $lessionplanId = !empty($postData['lessionplanId']) ? $postData['lessionplanId'] : '';
            $CONT_ID = !empty($postData['CONT_ID']) ? $postData['CONT_ID'] : '';

            $loData = $this->db->getLoByTopicId($topic_id);
            $loOption = array();
            $i = 0;
            foreach ($loData as $data) {
                // $option .= '<option >' . $i . '</option>';
                if (!empty($lessionplanId)) {
                    $count = $this->db->check_Lo_val_Exist($data['TOPIC_ID'], $data['LO_ID'], $lessionplanId);
                } elseif (!empty($CONT_ID)) {
                    $count = $this->db->check_Lo_val_Exist_contId($data['TOPIC_ID'], $data['LO_ID'], $CONT_ID);
                }

                if ($count == 0) {
                    $option .= '<option value="' . $data['TOPIC_ID'] . "_" . $data['LO_ID'] . '">' . $data['LO_NAME'] . '</option>';
                } else {
                    $option .= '<option selected value="' . $data['TOPIC_ID'] . "_" . $data['LO_ID'] . '">' . $data['LO_NAME'] . '</option>';
                }
                //$loOption[$data['TOPIC_ID'] . "_" . $data['LO_ID']] = $data['LO_NAME'];
                $i++;
            }

            echo $option;
            die;
        }
    }

    //save lession plan
    function addLessonPlanAction() {
        $subject_id = $this->params('id');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();

        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $catStr = (!empty($postData['TOPIC_ID'])) ? $postData['TOPIC_ID'] : '';
            $catArr = (!empty($catStr)) ? explode(',', $catStr) : [];
            //  print_r($catArr); die;
            // echo "<pre>"; print_r($postData['learning_objective']); die;
            $addForm = new AddLessonPlanForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail);
            $catgFilter = new AddLessonPlanInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            //$catgFilter->getInputFilter()->get('subject_id')->setRequired(true);
            //$catgFilter->getInputFilter()->get('CLASS_ID')->setRequired(true);
            $addForm->setInputFilter($catgFilter->getInputFilter());
            $addForm->setData($request->getPost());
            $err = 0;
            $translator = $this->getServiceLocator()->get('translator');
//            if (empty($postData['grade']) || $postData['grade'] < 1 || empty($postData['subject_id']) || $postData['subject_id'] < 1) {
//                $err = 1;
//                $msg = $translator->translate("Grade and Subject both are required");
//                $result = ['result' => false, 'message' => $msg, 'target' => '#clssub'];
//            }
            //$postData = $request->getPost()->toarray();
            $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
            $this->db = new GradeTable($dbadapter);
            $getRequirementList = $this->db->getRequirementList($postData['lession_plan_id']);
            if (empty($postData['lock_until']) && !empty($postData['is_unlock'])) {
                $mess = Array('lock_until' => Array('isEmpty' => $translator->translate('Please select date')));
                $result = ['result' => false, 'message' => $mess];
                $viewModel->setVariables(['data' => $result]);
                return $viewModel;
            }

//             if (empty($postData['learning_objective']['0']) && !empty($postData['learning_objective']['0'])) {
//                 echo "hi";
//                 die("if ");
//                $mess = Array('learning_objective' => Array('isEmpty' => $translator->translate('Please add Learning objective')));
//                $result = ['result' => false, 'message' => $mess];
////                $viewModel->setVariables(['data' => $result]);
////                return $viewModel;
//            }






            if (isset($postData['lp_requirement'])) {
                if ($postData['lp_requirement'] != 'N') {

                    $preViousAdded = count($getRequirementList);
                    $countDeleteData = 0;
                    if (!empty($postData['delreq'])) {
                        $countDeleteData = count(explode(",", $postData['delreq']));
                    }


                    if ($preViousAdded) {
                        if ($countDeleteData && $countDeleteData == $preViousAdded) {
                            if (empty($postData['content_id'][0])) {
                                $mess = Array('lp_requirement' => Array('isEmpty' => $translator->translate('Please add requirement')));
                                $result = ['result' => false, 'message' => $mess];
                                $viewModel->setVariables(['data' => $result]);
                                return $viewModel;
                            }
                        }
                    } else {
                        if (empty($postData['content_id'][0])) {
                            $mess = Array('lp_requirement' => Array('isEmpty' => $translator->translate('Please select at least one content')));
                            $result = ['result' => false, 'message' => $mess];
                            $viewModel->setVariables(['data' => $result]);
                            return $viewModel;
                        }
                    }
                }
            }

            if (!$err) {
                if ($addForm->isValid()) {
//                    if (empty($postData['learning_objective'])) {
//                        $mess = Array('learning_objective[]' => Array('isEmpty' => $translator->translate('Please select Learning Objective')));
//                        $result = ['result' => false, 'message' => $mess];
//                        $viewModel->setVariables(['data' => $result]);
//                        return $viewModel;
//                    }
                    $this->initModelObject();
                    $id = (!empty($this->params()->fromQuery('student_id'))) ? $this->params()->fromQuery('student_id') : "";
                    $studentId = (!empty($id)) ? $id : $this->container->authDetail['USER_OID'];
                    $postData['userid'] = $studentId;
//                    $postData['userid'] = $this->container->authDetail['USER_OID'];
                    // print_r($postData);die;
                    $hash = "";
                    if (!empty($postData['lession_plan_id'])) {
                        $hash = '?pos=lp' . $postData['lession_plan_id'];
                    }
                    $result = $this->db->addLessionPlan($postData);

                    $redPath = $this->returnBasePath();
                    if ($result == 'Add') {
                        $lession_plan_id = $this->db->getLastAddedLp();
                    } else {
                        $lession_plan_id = $postData['lession_plan_id'];
                    }
                    if (!empty($postData['learning_objective'])) {
                        foreach ($postData['learning_objective'] as $lodata) {
                            $topicIdandLoId = explode("_", $lodata);
                            // print_r($topicIdandLoId);
                            $conditions = array('TOPIC_ID' => $topicIdandLoId['0'], 'ST_LO_ID' => $topicIdandLoId['1'], 'LESSONPLAN_ID' => $lession_plan_id);
                            $this->db->deleteData('t_cm_mgr_lessonplan_lo', $conditions);
                            $InsData = [];
                            $InsData = ['TOPIC_ID' => $topicIdandLoId['0'], 'ST_LO_ID' => $topicIdandLoId['1'], 'LESSONPLAN_ID' => $lession_plan_id];
                            $this->db->insertData('t_cm_mgr_lessonplan_lo', $InsData);
                            // print_r($lodata);
                        }
                    }

                    if ($result == 'Add') {
                        $lession_plan_id = $this->db->getLastAddedLp();

                        $this->db->deleteData('t_cm_lessonplan_topic', ['LESSONPLAN_ID' => $lession_plan_id]);
                        for ($i = 0; $i < count($catArr); $i++) {
                            $InsData = [];
                            $InsData = ['LESSONPLAN_ID' => $lession_plan_id, 'TOPIC_ID' => $catArr[$i]];
                            $this->db->insertData('t_cm_lessonplan_topic', $InsData);
                        }

// $hash = '?pos=lp' . $lession_plan_id;
                        // $redPath = $redPath . '/grade/lesson-plan/' . $hash;
                        if (!empty($id)) {
                            $redUrl = $this->url()->fromRoute('grade', ['action' => 'lesson-plan', 'id' => $postData['SUBJECT_ID']], ['query' => ['student_id' => $id]]);
                        } else {
                            $redUrl = $this->url()->fromRoute('grade', ['action' => 'lesson-plan', 'id' => $postData['SUBJECT_ID']]);
                        }

//                     $result = ['result' => true, 'message' => 'Lesson plan has been saved successfully', 'redirectUrl' => $redUrl];
                        $result = ['result' => true, 'redirectUrl' => $redUrl];
                    } else if ($result == 'Update') {

                        $this->db->deleteData('t_cm_lessonplan_topic', ['LESSONPLAN_ID' => $postData['lession_plan_id']]);
                        for ($i = 0; $i < count($catArr); $i++) {
                            $InsData = [];
                            $InsData = ['LESSONPLAN_ID' => $postData['lession_plan_id'], 'TOPIC_ID' => $catArr[$i]];
                            $this->db->insertData('t_cm_lessonplan_topic', $InsData);
                        }
                        if (!empty($id))
                            $redUrl = $this->url()->fromRoute('grade', ['action' => 'lesson-plan', 'id' => $postData['SUBJECT_ID']], ['query' => ['student_id' => $id]]);
                        else
                            $redUrl = $this->url()->fromRoute('grade', ['action' => 'lesson-plan', 'id' => $postData['SUBJECT_ID']]);


                        // $redPath = $redPath . '/grade/lesson-plan/' . $hash;
                        $result = ['result' => true, 'message' => '', 'redirectUrl' => $redUrl];
                    } else {
                        $result = ['result' => false, 'message' => 'DB:Error'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $addForm->getMessages()];
                }
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //open popup dynamically...
    function openPopupAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $requestData = $this->getRequest()->getQuery()->toArray();
        $translator = $this->getServiceLocator()->get('translator');
        $viewModel = $this->CommonClass()->openPopUp($viewModel, $requestData);
        $file = $requestData['file'];
        if ($file == 'add-syllabus') {
            $this->initModelObject();
            $catFlag = isset($requestData['catFlag']) ? $requestData['catFlag'] : 'M';
            $subjectId = $requestData['subjectId'];
            $changeParent = $this->changeParent($subjectId);
            $parentCat = $requestData['parentCat'];
            $cat_name = (isset($requestData['cat_name'])) ? $requestData['cat_name'] : '';
            $mode = 'Add';
            $catgName = '';
            if (!empty($requestData['mode'])) {
                $mode = $requestData['mode'];
                $catgName = $this->db->getCategoryNameById($subjectId, $parentCat);
            }
            $getupPathArray = [];
            if (!empty($parentCat)) {
                $getupPathArray = $this->db->getCategoryPathUpward($subjectId, $parentCat);
                $getafterCatArray = $this->db->getAllChildCatByParent($subjectId, $parentCat);
            } else {
                $getafterCatArray = $this->db->getAllRootLevelCategory($subjectId);
            }
            $form = new AddSyllabusForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $subjectId, $parentCat, $catFlag);
            $viewModel->setVariables(['form' => $form, 'subjectId' => $subjectId, 'parentCat' => $parentCat, 'getupPathArray' => $getupPathArray, 'getafterCatArray' => $getafterCatArray, 'mode' => $mode, 'catgName' => $catgName, "changeParent" => $changeParent, 'catFlag' => $catFlag]);
        }


        if ($file == 'add-lesson-plan') {
            $contentId = !empty($requestData['contentId']) ? $requestData['contentId'] : '';

            $subject_id = $requestData['id'];
            $lessionPlanId = !empty($requestData['lessionPlanId']) ? $requestData['lessionPlanId'] : '';
            $this->db = new GradeTable($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $navigationArr = $this->db->getCurriculumNavigation($subject_id, "topic");
            $tab = 'add-lesson-plan';

            $navigation = (!empty($navigationArr)) ? $navigationArr['GRADE_NAME'] . ' / ' . $navigationArr['SUBJECT_NAME'] : '';

            $lp_id = (!empty($requestData['second_id'])) ? $requestData['second_id'] : '';
            $this->initModelObject();
            $mode = (empty($lp_id)) ? 'Add' : 'Edit';
            $form = new AddLessonPlanForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail, $lp_id, '', $subject_id);
            $form->get('SUBJECT_ID')->setValue($subject_id);
            $prerequisite = array();
            $SUBJECTData = [];
            $lessionPlanData = [];
            $strSection = '';
            $contentType = array();
            $getRequirementList = array();
            $lessionPlanData['LP_POSITION_ID'] = '';
            $this->initModelObject();
            $gradeData = $this->db->getGradeDataByOrgId($this->container->authDetail['ORG_ID']);
            $condArr = array();

            $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
            $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
            $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];
            $condArr['subject_id'] = $subject_id;
            $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);

            $lpData = $this->db->getLessonPlanData($condArr, $userIds);
            //echo "<pre>"; print_r($lpData); die;
            //$lpData = $this->db->getLessonPlanData($condArr, $this->container->authDetail['ORG_ID']);


            $countLp = count($lpData);
            if ($mode == 'Edit') {

                $lessionPlanData = $this->db->getLessonPlanById($lp_id);
                $lessionPlanData['LP_POSITION_ID'] = $this->db->getLessonPlanPositionId($lessionPlanData['LP_POSITION']);

                $prerequisite = $this->db->getPrerequisite($lp_id);

                $form->get('lession_plan_id')->setValue($lp_id);
                /** Bind data to form * */
                $form->get('LP_POSITION')->setValue($lessionPlanData['LP_POSITION_ID']);
                /** Bind data to form * */
                $form->setData($lessionPlanData);
                $contentType = $this->db->getContentType($lp_id);
                $getRequirementList = $this->db->getRequirementList($lp_id);
                $SUBJECTData = $this->db->getSubjectBySubjectId($lessionPlanData['SUBJECT_ID']);
                $strSection = '<option value="' . $SUBJECTData['SUBJECT_ID'] . '" selected>' . $SUBJECTData['SUBJECT_NAME'] . '</option>';
                $form->get('lock_until')->setValue((!empty($lessionPlanData['UNLOCK_ON']) ? $lessionPlanData['UNLOCK_ON'] : ''));
            }
            // $prerequisite = $this->db->getPrerequisite($lession_plan_id);
            $viewModel->setVariables(['form' => $form, 'contentId' => $contentId, 'navigation' => $navigation, 'lessionPlanId' => $lessionPlanId, 'tab' => $tab, 'subject_id' => $subject_id, 'mode' => $mode, "gradeData" => $gradeData, "SUBJECTData" => $strSection, 'lpdetail' => $lessionPlanData, 'lpCount' => $countLp, 'prerequisite' => $prerequisite, 'getRequirementList' => $getRequirementList, 'contentType' => $contentType]);
        }

        /** used to display summative-test form. */
        if ($file == 'add-summative-test') {
            $edit_from = !empty($requestData['edit_from']) ? $requestData['edit_from'] : null;
            $quizId = !empty($requestData['second_id']) ? $requestData['second_id'] : null;
            $subject_id = $requestData['id'];
            $testData = [];
            $this->db = new GradeTable($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));

            $condArr['subject_id'] = $subject_id;
            $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
            $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];
            $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
            $userIds = $this->db->getuserIdsByOrgId($condArr['ORG_ID']);
            $lpData = $this->db->getLessonPlanData($condArr, $userIds);

            $form = new \Secure\Form\Grade\AddSummativeTestForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail, $lpData);
            $gradeData = $this->db->getGradeDataByOrgId($condArr['ORG_ID']);

            if (!empty($quizId)) {
                /** Get for associated data to displayed in edit mode. */
                $testData = $this->db->fetchData('t_master_test', ['t_master_test.QUIZ_ID' => $quizId, 't_master_test.SUBJECT_ID' => $subject_id, 't_master_test.QUIZ_TYPE' => 'ST'], [], 'ST_POSITION', false);
                $testData['ST_NAME'] = $testData['TITLE'];
                $form->setData($testData);

                /** fetch data for display LP selection HTML */
                $condArr['LP_POSITION'] = $testData['ST_POSITION'];
                $lpDetail = !empty($condArr['LP_POSITION']) ? $this->db->getLessonPlanData($condArr, $userIds) : [];
                /** Get data to displayed checked/unchecked check-boxes. */
                $joins[] = ['t_cm_lessonplan_master', 't_cm_lessonplan_master.LESSONPLAN_ID = t_mgr_test_lessonplan.LESSONPLAN_ID', ['LP_POSITION', 'LP_NAME'], 'LEFT'];
                $lpTestDetail = $this->db->fetchData('t_mgr_test_lessonplan', ['t_mgr_test_lessonplan.QUIZ_ID' => $testData['QUIZ_ID']], ['LESSONPLAN_ID'], null, true, null, null, null, null, null, null, $joins);

                $lpTestLpArray = [];
                if (count($lpTestDetail)) {
                    foreach ($lpTestDetail as $lpTestData) {
                        $lpTestLpArray[] = $lpTestData['LESSONPLAN_ID'];
                    }
                }
            }

            $viewModel->setVariables([
                'form' => $form,
                'subject_id' => $subject_id,
                'testdetail' => $testData,
                'lpDetail' => isset($lpDetail) ? $lpDetail : [],
                'lpTestDetail' => isset($lpTestLpArray) ? $lpTestLpArray : [],
                'lpCount' => count($lpData),
                'quizId' => !empty($quizId) ? $quizId : 0,
                'edit_from' => $edit_from
            ]);
        }
        //to show category tree
        if ($file == 'category-tree') {
            $subjectId = $requestData['subjectId'];
            $catFlag = $requestData['catFlag'];
            $this->initModelObject();
            $catTreeWithHtml = $this->printCatTree($subjectId, $catFlag);
            $viewModel->setVariables(['subjectId' => $subjectId, 'catTreeWithHtml' => $catTreeWithHtml]);
        }
        if ($file == 'learning-objective') {
            $this->initModelObject();
            $viewModel->setVariables(['grade_batch_id' => 'ww', 'catTreeWithHtml' => 'ww']);
        }
        if ($file == 'popup_add_teb_content') {
            $this->initModelObject();
            $content_id = $requestData['content_id'];
            $contDetail = array();
            $contDetail = (!empty($contDetail[0])) ? $contDetail[0] : array();
            //echo "<pre>";print_r($contDetail);die;
            $condArr['subject_id'] = $requestData['subject_id'];
            $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);
            $lpData = $this->db->getLessonPlanData($condArr, $userIds);
            $viewModel->setVariables(['contDetail' => $contDetail, 'lpData' => $lpData]);
        }
        //edit lesson paln
        if ($file == 'edit-lesson-plan') {
            $this->initModelObject();
            $lession_plan_id = $requestData['lessionplan_id'];
            //$parentCat = $requestData['catId'];
            $mode = 'Edit';
            $lpdetail = $this->db->getLessonPlanDetail($lession_plan_id);
            $getGradeId = []; //$this->db->getGradeIdByClassId($lpdetail['CLASS_ID']);
            $getafterCatArray = array();
            if (!empty($lpdetail['CLASS_ID'])) {
                $getafterCatArray = $this->db->getAllLessionPlanByClass($lpdetail['CLASS_ID'], $lession_plan_id, $lpdetail['SUBJECT_ID']);
            }
            $lpdetail['LP_POSITION_ID'] = $this->db->getLessonPlanPositionId($lpdetail['CLASS_ID'], $lpdetail['LP_POSITION']);
            $form = new AddLessonPlanForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail, $lession_plan_id, $lpdetail['CLASS_ID'], $lpdetail['SUBJECT_ID']);

            $prerequisite = $this->db->getPrerequisite($lession_plan_id);
            $contentType = $this->db->getContentType($lession_plan_id);
            $topic = []; //$this->db->getAllTopic($lession_plan_id);
            $getRequirementList = $this->db->getRequirementList($lession_plan_id);
            $gradeData = $this->db->getGradeDataByOrgId($this->container->authDetail['ORG_ID']);
            $viewModel->setVariables(['form' => $form, 'gradeData' => $gradeData, 'getafterCatArray' => $getafterCatArray, 'mode' => $mode, 'lpdetail' => $lpdetail, 'prerequisite' => $prerequisite, "contentType" => $contentType, 'lession_plan_id' => $lession_plan_id, 'getRequirementList' => $getRequirementList, "grade_id" => $getGradeId, "topic" => $topic, 'subjectName' => $subjectName]);
        }
        //to add batch/year popup
        if ($file == 'popup_add_batch') {
            $form = new AddBatchForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID']);
            $viewModel->setVariables(['form' => $form]);
        }
        if ($file == 'popup_pull_grade') {
            $org_id = $this->container->authDetail['ORG_ID'];
            $this->initModelObject();
            $gardes = $this->db->getAllGradefromAdmByOrgId($org_id);
            $viewModel->setVariables(['batch_id' => $requestData['batch_id'], 'gardes' => $gardes]);
        }
        //to edit batch
        if ($file == 'popup_edit_batch') {
            $batchId = $requestData['id'];
            $this->initModelObject();
            $batchDetails = $this->db->getBatchDetails($batchId, $this->container->authDetail['ORG_ID']);
            $form = new AddBatchForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID'], $batchId);
            $viewModel->setVariables(['batchDetails' => $batchDetails, 'form' => $form]);
        }
        //to add class
        if ($file == 'popup_add_class') {
            $form = new AddClassForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID']);
            $gradeId = $requestData['gradeId'];
            $viewModel->setVariables(['form' => $form, 'gradeId' => $gradeId]);
        }
        //to edit class
        if ($file == 'popup_edit_class') {
            $id = $requestData['id'];
            $this->initModelObject();
            $classDetail = $this->db->getClassDetail($id);
            $form = new AddClassForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID'], $id);
            $viewModel->setVariables(['classDetail' => $classDetail, 'form' => $form]);
        }
        //add subjet popup
        if ($file == 'popup_add_subject') {
            $viewModel = $this->setModelVarForPopupSubject($viewModel, $requestData);
        }
        //to delete category
        if ($file == 'popup_delete_syllabus') {
            $subjectId = $requestData['subjectId'];
            $catId = $requestData['parentCat'];
            $viewModel->setVariables(['subjectId' => $subjectId, 'catId' => $catId]);
        }
        //to add enrich content
        if ($file == 'popup_add_ec') {
            $lpId = $requestData['lpId'];
            //$ecData = $this->getECDataFromCS($requestData);
            $viewModel->setVariables(['lpId' => $lpId]);
        }
        if ($file == 'popup_delete_confirmation') {
            $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
            $questionHelper = $viewHelperManager->get('QuestionPreviewHelper');

            $deleteMsg = (!empty($requestData['deleteMsg'])) ? $requestData['deleteMsg'] : null;
            $flagOk = 1;
            if (!empty($deleteMsg))
                $deleteMsg = $translator->translate($deleteMsg);
            $ID = (!empty($requestData['ID'])) ? $requestData['ID'] : null;
            /*
              $this->initModelObject();
              $contData = $this->db->getContentByContentId($ID);
              if(!empty($contData['CONTTYPE_ID']) && $contData['CONTTYPE_ID']==11){
              $submission = $this->db->getAssignmentSubmittedFile($ID);
              if(count($submission)){
              $deleteMsg = $translator->translate("Already in use");
              $flagOk = 0;
              }
              } */
            $viewModel->setVariables(['deleteMsg' => $deleteMsg, "ID" => $ID, 'flagOk' => $flagOk]);
        }

        /** Used to enable/disable delete test pop-up as attempting by student. */
        if ($file == 'popup_delete_summativetest') {
            $quizId = $requestData['id'];
            $this->initModelObject();
            $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
            $questionHelper = $viewHelperManager->get('QuestionPreviewHelper');

            $deleteMsg = (!empty($requestData['deleteMsg'])) ? $translator->translate($requestData['deleteMsg']) : null;
            $is_test_attempeted = $this->db->countData('t_usr_quiz_attempt', ['QUIZ_ID' => $quizId]);
            $flagOk = ($is_test_attempeted) ? true : false;

            $viewModel->setVariables(['deleteMsg' => $deleteMsg, "ID" => $quizId, 'flagOk' => $flagOk]);
        }

        /** Used to enable/disable delete final test pop-up as attempting by student. */
        if ($file == 'popup_delete_finaltest') {
            $quizId = $requestData['id'];
            $this->initModelObject();
            $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
            $questionHelper = $viewHelperManager->get('QuestionPreviewHelper');

            $deleteMsg = (!empty($requestData['deleteMsg'])) ? $translator->translate($requestData['deleteMsg']) : null;
            $is_test_attempeted = $this->db->countData('t_usr_quiz_attempt', ['QUIZ_ID' => $quizId]);
            $flagOk = ($is_test_attempeted) ? true : false;

            $viewModel->setVariables(['deleteMsg' => $deleteMsg, "ID" => $quizId, 'flagOk' => $flagOk]);
        }

        if ($file == 'popup_add_atb') {
            $ID = (!empty($requestData['lpId'])) ? $requestData['lpId'] : null;
            $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
            $adm = new AdministratorTable($dbadapter);
            $org_id = $this->container->authDetail['ORG_ID'];
            $allPurchasedBooks = $adm->getAllAtbBook($org_id);
            $viewModel->setVariables(['lpId' => $ID, 'books' => $allPurchasedBooks]);
        }
        if ($file == 'popup_add_placeholder') {
            $lpId = (!empty($requestData['lpId'])) ? $requestData['lpId'] : null;
            $CONT_ID = (!empty($requestData['CONT_ID'])) ? $requestData['CONT_ID'] : null;
            $title = (!empty($requestData['title'])) ? $requestData['title'] : null;
            $viewModel->setVariables(['lpId' => $lpId, 'title' => $title, "CONT_ID" => $CONT_ID]);
        }
        if ($file == 'popup_edit_lol') {
            $lpId = (!empty($requestData['lpId'])) ? $requestData['lpId'] : null;
            $CONT_ID = (!empty($requestData['CONT_ID'])) ? $requestData['CONT_ID'] : null;
            $title = (!empty($requestData['title'])) ? $requestData['title'] : null;
            $viewModel->setVariables(['lpId' => $lpId, 'title' => $title, "CONT_ID" => $CONT_ID]);
        }
        if ($file == 'popup_preview_widget') {
            $url = (!empty($requestData['url'])) ? $requestData['url'] : null;
            $filetype = (!empty($requestData['filetype'])) ? $requestData['filetype'] : null;
            $ext = (!empty($requestData['ext'])) ? $requestData['ext'] : null;
            //echo $filetype." => ".$url; die;
            $viewModel->setVariables(['url' => $url, 'filetype' => $filetype, 'ext' => $ext]);
        }

        if ($file == 'popup_lp_add_liveclass') {
            $form = new AddLiveClassForm('');
            $lp_id = (isset($requestData['lp_id'])) ? $requestData['lp_id'] : '';


            $viewModel->setVariables(['form' => $form, 'lp_id' => $lp_id]);
        }


        return $viewModel;
    }

    private function getCommonClass() {
        $commonClass = new Plugin\CommonClass();
        $commonClass->setController($this);
        return $commonClass;
    }

    /**
     * @desc used to display standard listing associated with specified country via API.
     * @param {any} $countryName | specified country name through country id.
     * @param {mix array} $navigation | used for back-path navigation purposes.
     */
    public function listTopicsDetailAction() {
        $request = $this->getRequest();
        $postData = $request->getPost();
        $this->db = new GradeTable($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
        $ids = $postData['ids'];
        $newData = '';
        if (!empty($ids)) {
            $topicsData = $this->db->getTopicsByTopicsIds($ids);
            if (!empty($topicsData)) {
                foreach ($topicsData as $index => $item) {
                    $newData .= '<tr id="tr_63">';
                    $newData .= '<td width="100%" class="pl-20">' . $item['CAT_NAME'] . '</td>';
                    $newData .= '<td class=" pr-20"><a href="javascript:void(0)" class="text-danger remove-topic-from-list" del-id="' . $item['CAT_ID'] . '"><i class="icon-cross3"></i></a></td>';
                    $newData .= '</tr>';
                }
            }
        }
        echo $newData;
        die;
    }

    public function openContentPopupAction() {
        $translator = $this->getServiceLocator()->get('translator');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $requestData = $this->getRequest()->getQuery()->toArray();
        $viewModel = $this->CommonClass()->openPopUp($viewModel, $requestData);
        $file = $requestData['file'];

        $this->db = new GradeTable($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));

        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';

        $subject_id = (!empty($requestData['subId'])) ? $requestData['subId'] : '';
        $lessonPlanId = (!empty($requestData['lesson_plan_id'])) ? $requestData['lesson_plan_id'] : '';
        $contentId = (!empty($requestData['content_id'])) ? $requestData['content_id'] : null;
        $isEnrichment = (!empty($requestData['isEnrichment'])) ? true : false;

        $navigationArr = $this->db->getCurriculumNavigation($subject_id, "topic");

        $navigation = (!empty($navigationArr)) ? $navigationArr['GRADE_NAME'] . ' / ' . $navigationArr['SUBJECT_NAME'] : '';

        $response = $this->db->getTopicsBySubjectId($subject_id);
        $topicArr = [];
        if ($response) {
            foreach ($response as $topic) {
                $topicArr[$topic['CAT_ID']] = $topic['CAT_NAME'];
            }
        }
        switch ($file) {
            case "content-text":
                $lpForm = new AddLpTextForm();
                $tab = 'text-content';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('CONT_SRC')->setValue($contentData['CONT_SRC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;
            case "content-link":
                $lpForm = new AddLpLinkForm();
                $tab = 'link-content';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('CONT_SRC')->setValue($contentData['CONT_SRC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-embed":
                $lpForm = new AddLpEmbedForm();
                $tab = 'embed-content';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('CONT_SRC')->setValue($contentData['CONT_SRC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;
            case "content-video":
                $lpForm = new AddLpVideoForm();
                $tab = 'video-content';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('BACKING_FILE')->setValue($contentData['CONT_SRC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;
            case "content-widget":
                $lpForm = new AddLpWidgetForm();
                $tab = 'widget-content';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('BACKING_FILE')->setValue($contentData['BACKING_FILE']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;
            case "content-audio":
                $lpForm = new AddLpAudioForm();
                $tab = 'widget-audio';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('BACKING_FILE')->setValue($contentData['BACKING_FILE']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-image":
                $lpForm = new AddLpImageForm();
                $tab = 'image-audio';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $standardTable->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    //$lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-scorm":
                $lpForm = new AddLpImageForm();
                $tab = 'tab-scorm';
                $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);

                //$lpId = $requestData['lpId'];
//                $viewModel->setVariables(['lpId' => $lpId]);

                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lpId' => $lessonPlanId,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-document":
                $lpForm = new AddLpDocumentForm();
                $tab = 'document-audio';
                if (!$isEnrichment) {
                    $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                }
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    //$lpForm->get('TEXT_SRC')->setValue($contentData['TEXT_SRC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'lpForm' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-live-class":
                $lpForm = new AddLiveClassForm();
                $tab = 'live-class';
                $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'form' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            case "content-assignment":
                $lpForm = new AddAssignmentForm();
                $tab = 'assignment';
                $lpForm->get('LESSONPLAN_ID')->setValue($lessonPlanId);
                $contentData = [];
                if (!empty($contentId)) {
                    $contentData = $this->db->getContentByContentId($contentId);
                    $lpForm->get('CONT_TITLE')->setValue($contentData['CONT_TITLE']);
                    $lpForm->get('CONT_DESC')->setValue($contentData['CONT_DESC']);
                    $lpForm->get('TOPIC_ID')->setValue($contentData['TOPIC_IDS']);
                    $isEnrichment = true;
                }

                $dataVariable = array(
                    'navigation' => $navigation,
                    'form' => $lpForm,
                    'tab' => $tab,
                    'subject_id' => $subject_id,
                    'lang' => $lang,
                    'contentData' => $contentData,
                    'lessonPlanId' => $lessonPlanId
                );
                if ($isEnrichment) {
                    $dataVariable['isEnrichment'] = true;
                }
                if (!empty($contentId)) {
                    $dataVariable['contentId'] = $contentId;
                }
                $viewModel->setVariables($dataVariable);

                break;

            default :
                break;
        }
        return $viewModel;
    }

    //delete data dynamically...
    function deleteDataAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $lpId = '';
            $requestData = $request->getQuery()->toArray();
            $ID = $requestData['ID'];
            $deleteAction = $requestData['deleteAction'];
            $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
            $this->db = new GradeTable($dbadapter);
            if ($deleteAction == 'grade') {
                $success = $this->db->deleteGrade($ID);
            }
            if ($deleteAction == 'batch') {
                $success = $this->db->deleteBatch($ID);
            }
            if ($deleteAction == 'class') {
                $success = $this->db->deleteClass($ID);
            }
            if ($deleteAction == 'lessonplan') {
                $this->deleteLessonplanByLpId($ID);
                $this->db->deleteLessonplanPrerequisite($ID);
                $this->db->deleteLessonplanRequirement($ID);
                //  $this->db->deleteLessonplanTopic($ID);
                $success = $this->db->deleteLessonplan($ID);
            }
            if ($deleteAction == 'content') {
                $lpId = $requestData['lpId'];
                $getCourseId = $this->db->getCourseId($ID);
                if (!empty($getCourseId)) {
                    $this->deleteScorm($getCourseId);
                }

                $this->deleteContentByContId($ID);
                $success = 1;
            }
            if ($deleteAction == 'subject') {
                $success = $this->db->deleteSubject($ID);
            }
            if ($deleteAction == 'summativetest') {
                $success = 0;
                $is_test_deleted = $this->db->deleteData('t_master_test', ['QUIZ_ID' => $ID]);
                if ($is_test_deleted) {
                    $is_test_lp_deleted = $this->db->deleteData('t_mgr_test_lessonplan', ['QUIZ_ID' => $ID]);
                    $success = 1;
                }
            }
            if ($deleteAction == 'finaltest') {
                $success = 0;
                $is_test_deleted = $this->db->deleteData('t_master_test', ['QUIZ_ID' => $ID]);
                if ($is_test_deleted) {
                    $is_test_lp_deleted = $this->db->deleteData('t_master_test', ['QUIZ_ID' => $ID]);
                    $success = 1;
                }
            }
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $success
            ));
            return $jsonModel;
        }
    }

    function deleteLessonplanByLpId($lession_plan_id) {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $gradeTable = new GradeTable($dbadapter);
        $getLP = $gradeTable->getContentListByLpId($lession_plan_id);
        if (count($getLP)) {
            foreach ($getLP as $lpdta) {
                $this->deleteContentByContId($lpdta['CONT_ID']);
            }
        }
    }

    function deleteContentByContId($cont_id) {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $gradeTable = new GradeTable($dbadapter);
        //delete from aws
        $contData = $gradeTable->getContentByContentId($cont_id);
        $this->deleteFromFileServer($contData);
        $quizId = $gradeTable->getTestIdByContentId($cont_id);
        // delete  t_quiz_cnf_quiz_qus
        // $testCommonPlugin = new \Test\Controller\Plugin\TestCommonPlugin($this->getServiceLocator());
        //$testCommonPlugin->deleteTestById($quizId);
        $gradeTable->deleteQuiz($cont_id);
        //$gradeTable->deleteQuizQus($quizId);
        // Delete Data for Assignment
        if ($contData['CONTTYPE_ID'] == 11) {
            $assignmentTable = $this->initTable('Secure\Model\Assignment\AssignmentTable');
            $assignment_id = $assignmentTable->getAssignmentIdByContentId($cont_id);
            if ($assignment_id) {
                $assignmentTable->deleteAssignment($assignment_id);
            }
        }
        if ($contData['CONTTYPE_ID'] == 15) {
            $gradeTable = $this->initTable('Secure\Model\Grade\GradeTable');
            $gradeTable->deleteLiveClassData($cont_id);
        }
        $gradeTable->deleteContent($cont_id);
    }

    //delete file from AWS server
    function deleteFromFileServer($contData) {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $gradeTable = new GradeTable($dbadapter);
        $cont_id = $contData['CONT_ID'];
        //$contData = $gradeTable->getContentByContentId($cont_id);
        if (empty($contData['FILE_UID'])) {
            //REMOVE FROM S3
            if ($contData['CONTTYPE_ID'] == 4) {
                //remove images
                $contImages = $gradeTable->getContentImages($cont_id);
                if (count($contImages)) {
                    foreach ($contImages as $imgData) {
                        $this->removeS3File('CONTENT/' . $imgData['IMG_BACKING_FILE']);
                    }
                }
            } else if ($contData['CONTTYPE_ID'] == 7) {
                //remove widget
                if (!empty($contData['BACKING_FILE'])) {
                    $widgetExp = explode('/', $contData['BACKING_FILE']);
                    $this->removeS3Folder($widgetExp[0]);
                }
            } else if ($contData['CONTTYPE_ID'] == 11) {
                //remove assignments
                /*
                  $contAssignments = $gradeTable->getAssignmentFiles($cont_id);
                  if(count($contAssignments)){
                  foreach($contAssignments as $assData){
                  $this->removeS3File($assData['FILE_NAME']);
                  }
                  }
                  $submission = $gradeTable->getAssignmentSubmittedFile($cont_id);
                  if(count($submission)){
                  foreach($submission as $assData){
                  $this->removeS3File($assData['FILE_NAME']);
                  }
                  }
                 */
            } else if ($contData['CONTTYPE_ID'] == 5 || $contData['CONTTYPE_ID'] == 6 || $contData['CONTTYPE_ID'] == 8) {
                //remove others
                $this->removeS3File('CONTENT/' . $contData['BACKING_FILE']);
            }
        }
    }

    function removeS3File($keyname) {
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $config = $this->serviceLocator->get('config');
        $bucket = $config['s3bucket'];
        $result = $client->deleteObject(array(
            'Bucket' => $bucket,
            'Key' => $keyname
        ));
        $return = 1;
        return $return;
    }

    function removeS3Folder($folder) {
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $config = $this->serviceLocator->get('config');
        $bucket = $config['s3bucket'];
        //delete new directory inside LOL folder
        $resp = $client->deleteMatchingObjects($bucket, $folder);
        $return = 1;
        return $return;
    }

    //delete module
    function deleteSyllabusAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postData = $request->getPost()->toArray();
            $this->initModelObject();
            $currentCat = $postData['currentCat'];
            $deleteaction = $postData['deleteaction'];
            //echo '<pre>';print_r($postData);die;
            if ($deleteaction == "E") {
                $success = $this->db->DeleteEntireTreeByCategoryId($currentCat);
            } else {
                $success = $this->db->DeleteSelectedCategoryOnlyById($currentCat);
            }
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $success
            ));
            return $jsonModel;
        }
    }

    /**
     * @desc lesson plan: all listing with id
     * @return ViewModel
     */
    function enrichmentContentAction() {

        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $id = (!empty($this->params()->fromQuery('student_id'))) ? $this->params()->fromQuery('student_id') : "";
        $studentId = (!empty($id)) ? $id : $this->container->authDetail['USER_OID'];
        $subject_id = $this->params('id');
        if (empty($subject_id)) {
            $url = $this->returnBasePath() . '/curriculum';
            return $this->redirect()->toUrl($url);
        }
        $adm = new AdministratorTable($dbadapter);
        $lessonPlanId = ''; //$this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
        $condArr['USER_OID'] = $studentId;
        $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];

        /** to get tebian enable data */
        $orgdetail = $adm->getSchoolDetail($condArr['ORG_ID']);
        $is_tebian = $orgdetail['TEBYAN_ENABLE'];
        /** to get Tebian enable data end */
        $importedSubjects = $this->db->getAllImportedSubjects($this->container->authDetail['ORG_ID'], $subject_id);

        if (!empty($lessonPlanId))
            $condArr['LP_ID'] = $lessonPlanId;

        //$subject_id = (!empty($_GET['sub'])) ? $_GET['sub'] : null;
        $gradeid = (!empty($_GET['grade'])) ? $_GET['grade'] : null;
        $class_id = (!empty($_GET['cls'])) ? $_GET['cls'] : null;
        $createdby = (!empty($_GET['by'])) ? $_GET['by'] : null;
        $condArr['subject_id'] = $subject_id;
        $condArr['grade_id'] = '';
        $condArr['CREATED_BY'] = $createdby;
        $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);

//        if($this->container->authDetail['UT_ID']==2)
//        {
//            $userIds= $this->db->getadminIdsByOrgId($this->container->authDetail['ORG_ID'],$studentId);
//          }

        $lpData = $this->db->getLessonPlanData($condArr, $userIds);
        /** used to get ST test data to display purposes on page. */
        $stData = $this->db->fetchData('t_master_test', ['CREATED_BY' => $userIds, 'SUBJECT_ID' => $subject_id, 'QUIZ_TYPE' => 'ST'], [], 'ST_POSITION');

        /** Final test details */
        $ftTestDetail = $this->db->fetchData('t_master_test', ['SUBJECT_ID' => $subject_id, 'QUIZ_TYPE' => 'FT'], ['QUIZ_ID', 'QUIZ_TYPE', 'PUBLISH'], null, false);


        /** Get data to displayed at main page for selected LPs. */
        $joins[] = ['t_mgr_test_lessonplan', 't_mgr_test_lessonplan.QUIZ_ID = t_master_test.QUIZ_ID', ['LESSONPLAN_ID']];
        $joins[] = ['t_cm_lessonplan_master', 't_cm_lessonplan_master.LESSONPLAN_ID = t_mgr_test_lessonplan.LESSONPLAN_ID', ['LP_NAME']];
        $lpTestDetail = $this->db->fetchData('t_master_test', ['t_master_test.CREATED_BY' => $userIds, 't_master_test.SUBJECT_ID' => $subject_id, 't_master_test.QUIZ_TYPE' => 'ST'], ['QUIZ_ID'], 'LP_POSITION', true, null, null, null, null, null, null, $joins);

        /** Get ST positions array to get correct positioned list on page. */
        $stPositionData = [];
        if (count($stData)) {
            foreach ($stData as $data) {
                $stPositionData[] = $data['ST_POSITION'];
            }
        }

        $countLp = count($lpData);
        $getAllLpUser = $this->db->getAllLpUser($this->container->authDetail['ORG_ID']);

        $getAllLpGrade = $this->db->getGradesByOrgId($condArr);

        $getGradeSubjectName = $this->db->getGradesNameBySubjectId($subject_id);

        $lpTextForm = new AddLpTextForm();
        $lpLinkForm = new AddLpLinkForm();
        $lpEmbedForm = new AddLpEmbedForm();
        $lpImgForm = new AddLpImageForm();
        $lpVideoForm = new AddLpVideoForm();
        $lpAudioForm = new AddLpAudioForm();
        $lpWidgetForm = new AddLpWidgetForm();
        $lpDocumentForm = new AddLpDocumentForm();
        $lpQuizForm = new AddLpQuizForm();

        $batch = [];
        $userSessionDetails = $this->container->authDetail;
        $translator = $this->getServiceLocator()->get('translator');
        $academicYr = '<option value="">' . $translator->translate("Academic Year") . '</option>';
        $batch_id = (!empty($_GET['batch'])) ? $_GET['batch'] : null;

        $gradeList = '';
        $classList = '';
        $subjectList = '';

//        if (!empty($grade_id)) {
//            $teacher_id = null;
//            if ($this->container->authDetail['UT_ID'] == '3') {
//                $teacher_id = $this->container->authDetail['USER_OID'];
//            }
//            $class = $this->db->getClassByGrade($grade_id, $teacher_id);
//            if (count($class)) {
//                foreach ($class as $data) {
//                    $sel = "";
//                    if ($data['CLASS_ID'] == $class_id) {
//                        $sel = 'selected';
//                    }
//                    $classList .= '<option value="' . $data['CLASS_ID'] . '" ' . $sel . '>' . $data['CLASS_NAME'] . '</option>';
//                }
//            }
//        }
//        if (!empty($gradeid)) {
//            $subjects = $this->db->getSubjects($gradeid);
//            if (count($subjects)) {
//                foreach ($subjects as $data) {
//                    $sel = "";
//                    if ($data['SUBJECT_ID'] == $subject_id) {
//                        $sel = 'selected';
//                    }
//                    $subjectList .= '<option value="' . $data['SUBJECT_ID'] . '" ' . $sel . '>' . $data['SUBJECT_NAME'] . '</option>';
//                }
//            }
//        }
        $subjectDetail = $this->db->getSubjectDetail($subject_id);
        $viewModel->setVariables([
            'lpData' => $lpData,
            'stData' => $stData,
            'stPositionData' => $stPositionData,
            'lessonPlanId' => $lessonPlanId,
            'lpTextForm' => $lpTextForm,
            'lpLinkForm' => $lpLinkForm,
            'lpEmbedForm' => $lpEmbedForm,
            'lpImgForm' => $lpImgForm,
            'lpVideoForm' => $lpVideoForm,
            'lpAudioForm' => $lpAudioForm,
            'lpWidgetForm' => $lpWidgetForm,
            'lpDocumentForm' => $lpDocumentForm,
            'lpQuizForm' => $lpQuizForm,
            'lang' => $lang,
            'academicYr' => $academicYr,
            'gradeList' => $gradeList,
            'classList' => $classList,
            'subjectList' => $subjectList,
            'getAllLpUser' => $getAllLpUser,
            'getAllLpGrade' => $getAllLpGrade,
            'grade_id' => $gradeid,
            'subject_id' => $subject_id,
            'quiz_id' => !empty($subjectDetail['QUIZ_ID']) ? $subjectDetail['QUIZ_ID'] : null,
            'createdby' => $createdby,
            'userId' => $this->container->authDetail['USER_OID'],
            'countLp' => $countLp,
            'userSessionDetails' => $userSessionDetails,
            'importedSubjects' => $importedSubjects,
            'getGradeSubjectName' => $getGradeSubjectName,
            'student_id' => $id,
            'tebian_enable' => $is_tebian,
            'isAssessmentEnable' => $this->container->authDetail['TEST_ENABLE'],
            'orgId' => $this->container->authDetail['ORG_ID'],
            'lpTestDetail' => $lpTestDetail,
            'finalTestdata' => !empty($ftTestDetail['QUIZ_ID']) ? $ftTestDetail : null,
        ]);
        return $viewModel;
    }

    /**
     * @desc lesson plan: all listing with id
     * @return ViewModel
     */
    function lessonPlanAction() {

        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $id = (!empty($this->params()->fromQuery('student_id'))) ? $this->params()->fromQuery('student_id') : "";
        $studentId = (!empty($id)) ? $id : $this->container->authDetail['USER_OID'];
        $subject_id = $this->params('id');
        if (empty($subject_id)) {
            $url = $this->returnBasePath() . '/curriculum';
            return $this->redirect()->toUrl($url);
        }
        $adm = new AdministratorTable($dbadapter);
        $lessonPlanId = ''; //$this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
        $condArr['USER_OID'] = $studentId;
        $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];

        /** to get tebian enable data */
        $orgdetail = $adm->getSchoolDetail($condArr['ORG_ID']);
        $is_tebian = $orgdetail['TEBYAN_ENABLE'];
        /** to get Tebian enable data end */
        $importedSubjects = $this->db->getAllImportedSubjects($this->container->authDetail['ORG_ID'], $subject_id);

        if (!empty($lessonPlanId))
            $condArr['LP_ID'] = $lessonPlanId;

        //$subject_id = (!empty($_GET['sub'])) ? $_GET['sub'] : null;
        $gradeid = (!empty($_GET['grade'])) ? $_GET['grade'] : null;
        $class_id = (!empty($_GET['cls'])) ? $_GET['cls'] : null;
        $createdby = (!empty($_GET['by'])) ? $_GET['by'] : null;
        $condArr['subject_id'] = $subject_id;
        $condArr['grade_id'] = '';
        $condArr['CREATED_BY'] = $createdby;
        $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);

//        if($this->container->authDetail['UT_ID']==2)
//        {
//            $userIds= $this->db->getadminIdsByOrgId($this->container->authDetail['ORG_ID'],$studentId);
//          }

        $lpData = $this->db->getLessonPlanData($condArr, $userIds);
        /** used to get ST test data to display purposes on page. */
        $stData = $this->db->fetchData('t_master_test', ['CREATED_BY' => $userIds, 'SUBJECT_ID' => $subject_id, 'QUIZ_TYPE' => 'ST'], [], 'ST_POSITION');

        /** Final test details */
        $ftTestDetail = $this->db->fetchData('t_master_test', ['SUBJECT_ID' => $subject_id, 'QUIZ_TYPE' => 'FT'], ['QUIZ_ID', 'QUIZ_TYPE', 'PUBLISH'], null, false);


        /** Get data to displayed at main page for selected LPs. */
        $joins[] = ['t_mgr_test_lessonplan', 't_mgr_test_lessonplan.QUIZ_ID = t_master_test.QUIZ_ID', ['LESSONPLAN_ID']];
        $joins[] = ['t_cm_lessonplan_master', 't_cm_lessonplan_master.LESSONPLAN_ID = t_mgr_test_lessonplan.LESSONPLAN_ID', ['LP_NAME']];
        $lpTestDetail = $this->db->fetchData('t_master_test', ['t_master_test.CREATED_BY' => $userIds, 't_master_test.SUBJECT_ID' => $subject_id, 't_master_test.QUIZ_TYPE' => 'ST'], ['QUIZ_ID'], 'LP_POSITION', true, null, null, null, null, null, null, $joins);

        /** Get ST positions array to get correct positioned list on page. */
        $stPositionData = [];
        if (count($stData)) {
            foreach ($stData as $data) {
                $stPositionData[] = $data['ST_POSITION'];
            }
        }

        $countLp = count($lpData);
        $getAllLpUser = $this->db->getAllLpUser($this->container->authDetail['ORG_ID']);

        $getAllLpGrade = $this->db->getGradesByOrgId($condArr);

        $getGradeSubjectName = $this->db->getGradesNameBySubjectId($subject_id);

        $lpTextForm = new AddLpTextForm();
        $lpLinkForm = new AddLpLinkForm();
        $lpEmbedForm = new AddLpEmbedForm();
        $lpImgForm = new AddLpImageForm();
        $lpVideoForm = new AddLpVideoForm();
        $lpAudioForm = new AddLpAudioForm();
        $lpWidgetForm = new AddLpWidgetForm();
        $lpDocumentForm = new AddLpDocumentForm();
        $lpQuizForm = new AddLpQuizForm();

        $batch = [];
        $userSessionDetails = $this->container->authDetail;
        $translator = $this->getServiceLocator()->get('translator');
        $academicYr = '<option value="">' . $translator->translate("Academic Year") . '</option>';
        $batch_id = (!empty($_GET['batch'])) ? $_GET['batch'] : null;

        $gradeList = '';
        $classList = '';
        $subjectList = '';

//        if (!empty($grade_id)) {
//            $teacher_id = null;
//            if ($this->container->authDetail['UT_ID'] == '3') {
//                $teacher_id = $this->container->authDetail['USER_OID'];
//            }
//            $class = $this->db->getClassByGrade($grade_id, $teacher_id);
//            if (count($class)) {
//                foreach ($class as $data) {
//                    $sel = "";
//                    if ($data['CLASS_ID'] == $class_id) {
//                        $sel = 'selected';
//                    }
//                    $classList .= '<option value="' . $data['CLASS_ID'] . '" ' . $sel . '>' . $data['CLASS_NAME'] . '</option>';
//                }
//            }
//        }
//        if (!empty($gradeid)) {
//            $subjects = $this->db->getSubjects($gradeid);
//            if (count($subjects)) {
//                foreach ($subjects as $data) {
//                    $sel = "";
//                    if ($data['SUBJECT_ID'] == $subject_id) {
//                        $sel = 'selected';
//                    }
//                    $subjectList .= '<option value="' . $data['SUBJECT_ID'] . '" ' . $sel . '>' . $data['SUBJECT_NAME'] . '</option>';
//                }
//            }
//        }
        $subjectDetail = $this->db->getSubjectDetail($subject_id);
        $viewModel->setVariables([
            'lpData' => $lpData,
            'stData' => $stData,
            'stPositionData' => $stPositionData,
            'lessonPlanId' => $lessonPlanId,
            'lpTextForm' => $lpTextForm,
            'lpLinkForm' => $lpLinkForm,
            'lpEmbedForm' => $lpEmbedForm,
            'lpImgForm' => $lpImgForm,
            'lpVideoForm' => $lpVideoForm,
            'lpAudioForm' => $lpAudioForm,
            'lpWidgetForm' => $lpWidgetForm,
            'lpDocumentForm' => $lpDocumentForm,
            'lpQuizForm' => $lpQuizForm,
            'lang' => $lang,
            'academicYr' => $academicYr,
            'gradeList' => $gradeList,
            'classList' => $classList,
            'subjectList' => $subjectList,
            'getAllLpUser' => $getAllLpUser,
            'getAllLpGrade' => $getAllLpGrade,
            'grade_id' => $gradeid,
            'subject_id' => $subject_id,
            'quiz_id' => !empty($subjectDetail['QUIZ_ID']) ? $subjectDetail['QUIZ_ID'] : null,
            'createdby' => $createdby,
            'userId' => $this->container->authDetail['USER_OID'],
            'countLp' => $countLp,
            'userSessionDetails' => $userSessionDetails,
            'importedSubjects' => $importedSubjects,
            'getGradeSubjectName' => $getGradeSubjectName,
            'student_id' => $id,
            'tebian_enable' => $is_tebian,
            'isAssessmentEnable' => $this->container->authDetail['TEST_ENABLE'],
            'orgId' => $this->container->authDetail['ORG_ID'],
            'lpTestDetail' => $lpTestDetail,
            'finalTestdata' => !empty($ftTestDetail['QUIZ_ID']) ? $ftTestDetail : null,
        ]);
        return $viewModel;
    }

    function searchTebianEcAction() {
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $request = $this->getRequest();
        $requestData = $request->getPost()->toArray();
        $subject_id = $this->params('id');

        $local_subject_id = (!empty($_POST['local_subject_id'])) ? $_POST['local_subject_id'] : 0;
        $lessonPlanId = ''; //$this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
        $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
        $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];
        $importedSubjects = $this->db->getAllImportedSubjects($this->container->authDetail['ORG_ID'], $subject_id);

        $array["subject_ids"] = implode(",", $this->db->getAllImportedSubjects($this->container->authDetail['ORG_ID'], $subject_id));

        if ($subject_id) {
            $array["subject_ids"] = $subject_id;
        }
        $array['start'] = !empty($requestData['start']) ? $requestData['start'] : 0;
        $array['lenght'] = 12;
        $array['envflag'] = 'Y';

        if (!empty($requestData['quizType'])) {
            $enrichmentCont = array();
            $lpData = array();
            $countLp = count($lpData);

            $htmlViewPart = new ViewModel();
            $htmlViewPart->setTerminal(true)
                    ->setTemplate('secure/grade/tebian-ec-content-render.phtml')
                    ->setVariables([
                        'lpData' => $lpData,
                        'lang' => $lang,
                        'subject_id' => $subject_id,
                        'local_subject_id' => $local_subject_id,
                        'userId' => $this->container->authDetail['USER_OID'],
                        'countLp' => $countLp,
                        'enrichmentCont' => $enrichmentCont,
                        'importedSubjects' => $importedSubjects
            ]);

            $htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($htmlViewPart);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'responseData' => $htmlOutput
            ));
            return $jsonModel;
        }

        $enrichmentCont = array();
        //echo "<pre>"; print_r($enrichmentCont); die;
        $lpData = array();
        $countLp = count($lpData);

        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true)
                ->setTemplate('secure/grade/tebian-ec-render.phtml')
                ->setVariables([
                    'lpData' => $lpData,
                    'lang' => $lang,
                    'subject_id' => $subject_id,
                    'local_subject_id' => $local_subject_id,
                    'userId' => $this->container->authDetail['USER_OID'],
                    'countLp' => $countLp,
                    'enrichmentCont' => $enrichmentCont,
                    'importedSubjects' => $importedSubjects
        ]);

        $htmlOutput = $this->getServiceLocator()
                ->get('viewrenderer')
                ->render($htmlViewPart);

        $result['html'] = $htmlOutput;

        $jsonModel = new JsonModel();
        $jsonModel->setVariables(array(
            'data' => $result
        ));

        return $jsonModel;
    }

    function searchTebianLpAction() {
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $subject_id = $this->params('id');
        $lessonPlanId = ''; //$this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
        $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
        $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];


        $array["subject_ids"] = $subject_id;

        if ($subject_id) {
            $array["subject_id"] = $subject_id;
        }


        $lpData = array();
        $countLp = count($lpData);
        $local_subject_id = (!empty($_POST['local_subject_id'])) ? $_POST['local_subject_id'] : 0;
        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true)
                ->setTemplate('secure/grade/tebian-lp-render.phtml')
                ->setVariables([
                    'lpData' => $lpData,
                    'lang' => $lang,
                    'subject_id' => $subject_id,
                    'local_subject_id' => $local_subject_id,
                    'userId' => $this->container->authDetail['USER_OID'],
                    'countLp' => $countLp
        ]);

        $htmlOutput = $this->getServiceLocator()
                ->get('viewrenderer')
                ->render($htmlViewPart);

        $result['html'] = $htmlOutput;

        $jsonModel = new JsonModel();
        $jsonModel->setVariables(array(
            'data' => $result
        ));

        return $jsonModel;
    }

    function searchTebianContentAction() {
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $request = $this->getRequest();
        $requestData = $request->getPost()->toArray();
        $subject_id = $this->params('id');
        $array['start'] = !empty($requestData['start']) ? $requestData['start'] : 0;
        $array['length'] = !empty($requestData['length']) ? $requestData['length'] : 0;
        $array['search'] = (!empty($requestData['search'])) ? urlencode($requestData['search']) : "";

        $searchCont = array();



        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true)
                ->setTemplate('secure/grade/tebian-search-content.phtml')
                ->setVariables([
                    'searchCont' => $searchCont,
                    'lang' => $lang,
                    'subject_id' => $subject_id,
                    'userId' => $this->container->authDetail['USER_OID'],
        ]);

        $htmlOutput = $this->getServiceLocator()
                ->get('viewrenderer')
                ->render($htmlViewPart);

        $result['html'] = $htmlOutput;

        $jsonModel = new JsonModel();
        $jsonModel->setVariables(array(
            'data' => $result
        ));

        return $jsonModel;
    }

    function getStandardAction() {
        $id = (int) $_POST["countryId"];
        $translator = $this->getServiceLocator()->get('translator');
        $standardList = array();
        $option = '<option value="" > ' . $translator->translate("Select Standard") . ' </option>';
        if (count($standardList)) {
            foreach ($standardList as $val) {
                $option .= '<option value="' . $val['STANDARD_ID'] . '" > ' . $val['STANDARD_NAME'] . ' </option>';
            }
        }
        echo $option;
        die;
    }

    function getGradeAction() {
        $id = (int) $_POST["standardId"];
        $translator = $this->getServiceLocator()->get('translator');
        $gradeList = array();
        $option = '<option value="" > ' . $translator->translate("Select Grade") . ' </option>';
        if (count($gradeList)) {
            foreach ($gradeList as $val) {
                $option .= '<option value="' . $val['GRADE_ID'] . '" > ' . $val['GRADE_Name'] . ' </option>';
            }
        }
        echo $option;
        die;
    }

    function getSubjectApiAction() {
        $id = (int) $_POST["gradeId"];

        $translator = $this->getServiceLocator()->get('translator');
        $subjectList = array();

        $option = '<option value="" > ' . $translator->translate("Select Subject") . ' </option>';
        if (count($subjectList)) {
            foreach ($subjectList as $val) {
                $option .= '<option value="' . $val['SUBJECT_ID'] . '" > ' . $val['SUBJECT_NAME'] . ' </option>';
            }
        }
        echo $option;
        die;
    }

    /*     * ******** start from 8 july, 2015 *************** */

    //list batches/years
    function listBatchAction() {
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $this->initModelObject();
        $batchData = $this->db->getBatches($this->container->authDetail['ORG_ID']);
        $viewModel->setVariables(['batchData' => $batchData]);
        return $viewModel;
    }

    //list batches/years
    function listClassAction() {
        $gradeId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $this->initModelObject();
        $gradeDetail = $this->db->getGradeDetails($gradeId);
        $batchName = $this->db->getBatchName($gradeDetail['BATCH_ID'], $this->container->authDetail['ORG_ID']);
        if (empty($batchName)) {
            return $this->redirect()->toRoute('grade', array('action' => 'list-batch'));
        }
        //$dataList = $this->db->getClassList($this->container->authDetail['USER_OID'],$gradeId);
        $dataList = $this->db->getClassList(null, $gradeId);
        $viewModel->setVariables(['dataList' => $dataList, 'gradeId' => $gradeId, 'gradeDetail' => $gradeDetail, 'batchName' => $batchName]);
        return $viewModel;
    }

    /*
     * @desc Function written to add live classes
     */

    public function addclassAction() {
        // setting module specific layout
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $translator = $this->getServiceLocator()->get('translator');
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        // setting view type criteria
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $config = $this->getServiceLocator()->get('config');
        $virtualClassTable = $this->initTable('Secure\Model\Grade\GradeTable');
        $contentId = (int) $this->params()->fromRoute('id', 0);
        $result = ['result' => false, 'message' => ''];
        // Get attendee, presenter & language list
        $languageList = $timeZoneList = array();

        $languageList = $virtualClassTable->getLanguageList();
        $timeZoneList = $virtualClassTable->getTimeZoneList();


        $addClassForm = new AddClassForm($languageList, $timeZoneList, $dbadapter, $this->container->authDetail['ORG_ID']);
        //AddClassForm(null,$languageList, $timeZoneList, $dbadapter);

        $classDetails = $virtualClassTable->getClassDataByContentId($contentId);

        $classId = (!empty($classDetails['WIZIQ_CLASS_ID'])) ? $classDetails['WIZIQ_CLASS_ID'] : 0;
        $hour = $minute = '00';
        $AMPM = 'AM';

        $classInformation = array();
        $contentDeatil = $virtualClassTable->getContentDetailById($contentId);
        //echo "<pre>"; print_r($contentDeatil); die;
        $addClassForm->get('TITLE')->setValue($contentDeatil['CONT_TITLE']);
        $addClassForm->get('PRESENTER_DEFAULT_CONTROLS')->setValue('video');

        if ($classId > 0) {

            $hour = (!empty($classDetails['START_TIME'])) ? date('h', strtotime($classDetails['START_TIME'])) : $hour;
            $minute = (!empty($classDetails['START_TIME'])) ? date('i', strtotime($classDetails['START_TIME'])) : $minute;
            $AMPM = (!empty($classDetails['START_TIME'])) ? strtoupper(date('a', strtotime($classDetails['START_TIME']))) : $AMPM;

            $classInformation = $classDetails;
            $addClassForm->get('TIMEZONE_ID')->setValue($classDetails['TIMEZONE_ID']);
            $addClassForm->get('CREATE_RECORDING')->setValue($classDetails['CREATE_RECORDING']);
            $addClassForm->get('DURATION')->setValue($classDetails['DURATION']);
            $addClassForm->get('ATTENDEE_LIMIT')->setValue($classDetails['ATTENDEE_LIMIT']);
            $addClassForm->get('PRESENTER')->setValue($classDetails['PRESENTER']);
            $addClassForm->get('LANG_ID')->setValue($classDetails['LANG_ID']);
            $addClassForm->get('PRESENTER_DEFAULT_CONTROLS')->setValue($classDetails['PRESENTER_DEFAULT_CONTROLS']);
        } else {
            /* echo 'aaaaaaaaaaa<pre />'; print_r(); die('macro');
              $courseId = $virtualClassTable->getCourseDetailByContentId($contentId);
              $courseData = $virtualClassTable->getCourseDetailById($courseId);
              $addClassForm->get('LANG_ID')->setValue($courseData['COURSE_LANG']); */
            $addClassForm->get('ATTENDEE_LIMIT')->setValue($config['attendeeLimit']);
        }

        /*         * ****************  Add VC on submit form start ****************** */
        $request = $this->getRequest();
        $requestData = $request->getPost()->toArray();
        if ($request->isPost() && $request->isXmlHttpRequest()) {

            $addClassFilter = new AddClassInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addClassForm->setInputFilter($addClassFilter->getInputFilter());
            $addClassForm->setData($request->getPost());
            $isEmptyClassStartTime = true;
            if ($requestData['hour'] == '00') {
                $isEmptyClassStartTime = false;
            }
            if ($addClassForm->isValid() && $isEmptyClassStartTime) {

                //$postData['TITLE'] = $requestData['TITLE'];
                $postData['START_DATE'] = !empty($requestData['START_DATE']) ? $requestData['START_DATE'] : date('Y-m-d');
                $postData['START_TIME'] = date('G:i:s', strtotime($requestData['START_DATE'] . ' ' . $requestData['hour'] . ':' . $requestData['minute'] . ':00' . ' ' . $requestData['meridiem']));
                $postData['PRESENTER'] = $requestData['PRESENTER']; //$virtualClassTable->getPresenterUserOidByEmail($requestData['PRESENTER']); // Get presenter_id
                if (!empty($requestData['LANG_ID'])) {
                    $postData['LANG_ID'] = $requestData['LANG_ID'];
                }
                if (!empty($requestData['DURATION'])) {
                    $postData['DURATION'] = $requestData['DURATION'];
                }
                if (!empty($requestData['TIMEZONE_ID'])) {
                    $postData['TIMEZONE_ID'] = $requestData['TIMEZONE_ID'];
                }
                if (!empty($requestData['ATTENDEE_LIMIT'])) {
                    $postData['ATTENDEE_LIMIT'] = $requestData['ATTENDEE_LIMIT'];
                }
                if (!empty($requestData['PRESENTER_DEFAULT_CONTROLS'])) {
                    $postData['PRESENTER_DEFAULT_CONTROLS'] = $requestData['PRESENTER_DEFAULT_CONTROLS'];
                }
                if (!empty($requestData['CREATE_RECORDING'])) {
                    $postData['CREATE_RECORDING'] = $requestData['CREATE_RECORDING'];
                }
                // call create class WizIQ API
                $WizIq = new WizIqApi($config['WizIQsecretAcessKey'], $config['WizIQaccess_key'], $config['WizIQclassApiServiceUrl']);
                //remove comment when live
                // create params array
                $method = "create";
                if ($classId) {
                    $params['class_id'] = $classId;
                    $method = "modify";
                }
                $params['presenter_email'] = $virtualClassTable->getPresenterEmailByUserId($requestData['PRESENTER']);
                $params['start_time'] = date('Y-m-d G:i:s', strtotime($requestData['START_DATE'] . ' ' . $requestData['hour'] . ':' . $requestData['minute'] . ':00' . ' ' . $requestData['meridiem']));
                $params['title'] = $requestData['TITLE'];
                $params['duration'] = !empty($requestData['DURATION']) ? $requestData['DURATION'] : '';
                $params['time_zone'] = $virtualClassTable->getTimeZoneNameById($requestData['TIMEZONE_ID']);
                $params['attendee_limit'] = !empty($requestData['ATTENDEE_LIMIT']) ? $requestData['ATTENDEE_LIMIT'] : '';
                $params['create_recording'] = !empty($requestData['CREATE_RECORDING']) ? $requestData['CREATE_RECORDING'] : '';
                $params['return_url'] = '';
                $params['status_ping_url'] = '';
                $params['language_culture_name'] = $virtualClassTable->getLangCultNameByLangId($requestData['LANG_ID']);


                $response = $WizIq->createClass($params, $method);  //remove comment when live
                //remove These Lines  when live
                //###################Start ####################//
                /* $response['response'] = true;
                  $response['class_id'] = (!empty($params['class_id'])) ? $params['class_id'] : mt_rand(100000, 999999);
                  $response['presenter_url'] = 'https://www.wiziq.com/'; */
                //################### End ####################//
                // if WizIQ response was successfully, then insert details into db
                if ($response['response']) {
                    if ($classId) { // IF REQUEST COMES FOR EDIT CLASS
                        //$joinUrl = $virtualClassTable->getPresenterUrlByClassId($classId);
                        $joinUrl = $classDetails['PRESENTER_URL']; //$virtualClassTable->getPresenterUrlByClassId($classId);
                    } else { // IF REQUEST COMES FOR ADD CLASS
                        $joinUrl = $response['presenter_url'];
                    }
                    // create array to send mail

                    $commonHelper = $this->getServiceLocator()->get('ViewHelperManager')->get('CommonHelper');


                    $mailOptions['email'] = $params['presenter_email'];
                    $mailOptions['class_start_time'] = $params['start_time'];
                    $mailOptions['class_title'] = $params['title'];
                    $mailOptions['name'] = !empty($commonHelper->getUserFullName($postData['PRESENTER'])) ? $commonHelper->getUserFullName($postData['PRESENTER']) : 'User'; // get presenter name by presenter id
                    $mailOptions['join_url'] = $joinUrl;

                    if ($classId) { // IF REQUEST COMES FOR EDIT CLASS
                        $cntCondition = ['CONT_ID' => $contentId];

                        $virtualClassTable->updateData('t_cm_cnf_content', ['CONT_TITLE' => $requestData['TITLE']], $cntCondition);

                        $condition = ['WIZIQ_CLASS_ID' => $classId];
                        $message = $translator->translate('Class has been updated successfully');
                        $virtualClassTable->updateData('t_cm_cnf_liveclass', $postData, $condition);
                        // send mail to teacher during add class

                        $this->sendMailCreateClass($mailOptions, 'EDIT_CLASS'); //remove comment when live
                    } else { // IF REQUEST COMES FOR ADD CLASS
                        $postData['CONT_ID'] = $contentId;
                        $postData['WIZIQ_CLASS_ID'] = $response['class_id'];
                        $postData['PRESENTER_URL'] = isset($response['presenter_url']) ? $response['presenter_url'] : '';
                        $postData['RECORDING_URL'] = isset($response['recording_url']) ? $response['recording_url'] : '';
                        $message = $translator->translate('Class has been added successfully');

                        $cntCondition = ['CONT_ID' => $contentId];
                        $virtualClassTable->updateData('t_cm_cnf_content', ['CONT_TITLE' => $requestData['TITLE']], $cntCondition);
                        $result = $virtualClassTable->insertData('t_cm_cnf_liveclass', $postData);


                        //If course already subscribed, new class will auto subscriobed in that course
                        //add attendee for enrolled subject
                        $subjectId = $virtualClassTable->getSubjectIdByContentId($contentId);
                        $umTable = $this->initTable('Secure\Model\UserManagement\UserManagementTable');
                        $userIdArr = $umTable->getAllUserBySubjectId($subjectId);

                        $commonTable = $this->initTable('Secure\Model\CommonTable');

                        if (count($userIdArr) > 0) {
                            $postData2 = [];
                            $attendeeArr = [];
                            $j = 0;
                            foreach ($userIdArr as $usr) {
                                $username = $commonTable->getUserFullName($usr['USER_OID']);
                                $attendeeArr[$j]['attendee_id'] = $usr['USER_OID'];
                                $attendeeArr[$j]['attendee_name'] = empty($username) ? 'user ' . rand() : $username;
                                $attendeeArr[$j]['language_culture_name'] = $params['language_culture_name'];
                                $j++;
                            }
                            $response2 = $WizIq->AddAttendee($attendeeArr, $postData['WIZIQ_CLASS_ID']);

                            //echo '<pre>';print_r($response2);

                            foreach ($response2['attendees'] as $attendee) {
                                $postData2['VC_ID'] = $response2['class_id'];
                                $postData2['USER_OID'] = $attendee['attendee_id'];
                                $postData2['ATTENDEE_URL'] = $attendee['attendee_url'];
                                $virtualClassTable->insertData('t_cm_mgr_joinclass', $postData2);
                            }
                        }


                        // send mail to teacher during add class
                        $this->sendMailCreateClass($mailOptions, 'ADD_CLASS'); //remove comment when live
                    }
                    $lessonplan_id = $virtualClassTable->getLessonplanIdByContentId($contentId);
                    $LpArray = $virtualClassTable->getLessonPlanById($lessonplan_id);
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $contentId;
                    // $redPath = $this->returnBasePath() . '/grade/lesson-plan/';

                    $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'innerhtml' => true, 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => $translator->translate($response['errormsg'])];
                }
            } else {
                $messageArray = $addClassForm->getMessages();
                if (!$isEmptyClassStartTime) {
                    $messageArray['hour']['isEmpty'] = $translator->translate('Select class start time');
                }
                $result = ['result' => false, 'message' => $messageArray];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        /*         * ****************  Add VC on submit form End ****************** */

        $viewModel->setVariables(['addClassForm' => $addClassForm, 'data' => $result, 'contentId' => $contentId,
            'languageList' => $languageList, 'setHour' => $hour, 'setMinute' => $minute, 'setAMPM' => $AMPM, 'classInfo' => $classInformation
        ]);
        return $viewModel;
    }

    /*
     * @desc Used of this function to choose email template and call sendMail()
     * @param array $params
     * @param string $event
     *
     * @return boolean true/false
     */

    public function sendMailCreateClass($params, $event) {
        $params['baseUrl'] = $this->returnBasePath();
        if (!empty($params) && !empty($event)) {
            $emailPluginObj = new EmailPlugin();
            if ($event == 'ADD_USER') {
                $body = $emailPluginObj->setEmailTemplate('invite_user.phtml', $params);
            } else if ($event == 'EDIT_USER') {
                $body = $emailPluginObj->setEmailTemplate('edit_user.phtml', $params);
            } else if ($event == 'ADD_CLASS') {
                $body = $emailPluginObj->setEmailTemplate('add_class.phtml', $params);
            } else if ($event == 'EDIT_CLASS') {
                $body = $emailPluginObj->setEmailTemplate('edit_class.phtml', $params);
            } else if ($event == 'CANCEL_CLASS') {
                $body = $emailPluginObj->setEmailTemplate('cancel_class.phtml', $params);
            }

            return $emailPluginObj->sendMail($params['email'], $body);
        }

        return false;
    }

//    public function addclassAction() {
//        // setting module specific layout
//        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
//        $translator = $this->getServiceLocator()->get('translator');
//        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
//        // setting view type criteria
//        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
//        $config = $this->getServiceLocator()->get('config');
//        $gradeObj = new GradeTable($dbadapter);
//        $contentId = (int) $this->params()->fromRoute('id', 0);
//        $result = ['result' => false, 'message' => ''];
//        // Get attendee, presenter & language list
//        $languageList = $timeZoneList = array();
//        $languageList = $this->getLanguageList();
//        $timeZoneList = $this->getTimeZoneList();
//
//        $addClassForm = new AddClassForm(null,null,$dbadapter,$this->container->authDetail['ORG_ID']);
//        $filterObj = new AddClassInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
//
//        $request = $this->getRequest();
//        $requestData = $request->getPost()->toArray();
//        if ($request->isPost() && $request->isXmlHttpRequest()) {
//
//
//        }
//        $viewModel->setVariables(['addClassForm' => @$addClassForm, 'data' => @$result, 'contentId' => @$contentId,
//            'languageList' => $languageList, 'setHour' => @$hour, 'setMinute' => @$minute, 'setAMPM' => @$AMPM, 'classInfo' => @$classInformation
//        ]);
//        return $viewModel;
//    }
    //class detail with enrollment users
    function classDetailAction() {
        $classId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $classDetail = $this->db->getClassDetail($classId);
        $check = $this->db->checkClassDetailByOrgId($classId, $this->container->authDetail['ORG_ID']);
        if (!$check) {
            return $this->redirect()->toRoute('grade', array('action' => 'list-batch'));
        }
        $MemberDetailOfClass = $this->db->getMemberDetailOfClass($classId);
        //echo "<pre>"; print_r($MemberDetailOfClass);die;
        $viewModel->setVariables(['classDetail' => $classDetail, 'MemberDetailOfClass' => $MemberDetailOfClass]);
        return $viewModel;
    }

    //add batch
    function addBatchAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $addForm = new AddBatchForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID']);
            $filterObj = new AddBatchInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($filterObj->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $postData = $request->getPost()->toArray();
                $this->initModelObject();
                //add batch data
                $result = $this->db->addBatch($postData, $this->container->authDetail['ORG_ID']);
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-batch';
                    $result = ['result' => true, 'message' => 'Batch has been added successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //Edit batches/years
    function editBatchAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $addForm = new AddBatchForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID']);
            $filterObj = new AddBatchInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($filterObj->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $postData = $request->getPost()->toArray();
                $this->initModelObject();
                //add batch data
                $result = $this->db->editBatch($postData, $this->container->authDetail['ORG_ID']);
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-batch';
                    $result = ['result' => true, 'message' => 'Batch has been updated successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //Edit Class
    function editClassAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $addForm = new AddClassForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail['ORG_ID']);
            $filterObj = new AddClassInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($filterObj->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $postData = $request->getPost()->toArray();
                $gradeId = $postData['GRADE_ID'];
                $this->initModelObject();
                //add batch data
                $result = $this->db->editClass($postData, $this->container->authDetail['USER_OID']);
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-class/' . $gradeId;
                    $result = ['result' => true, 'message' => 'Class has been updated successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //remove batch garde of class
    function removeBatchGradeAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postData = $request->getPost()->toArray();
            $BATCH_GRADE_ID = $postData['BATCH_GRADE_ID'];
            $this->initModelObject();
            $success = $this->db->removeBatchGradeOfClass($BATCH_GRADE_ID);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $success
            ));
            return $jsonModel;
        }
    }

    //add LP content [in progress...Quiz/Ass pending]
    function addLpContentAction() {
        $contentId = $this->params('id'); //In edit mode
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        //print_r($postData);die;
        if ($request->isPost() && $request->isXmlHttpRequest()) {

            //add lp content as per content Type
            if ($postData['CONTTYPE_ID'] == 1) {

                $form = new AddLpTextForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpTextInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));

                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 2) {
                $form = new AddLpLinkForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpLinkInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 3) {
                $form = new AddLpEmbedForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpEmbedInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 4) {
                $form = new AddLpImageForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpImageInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 5) {
                $form = new AddLpVideoForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpVideoInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 6) {
                $form = new AddLpAudioForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpAudioInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 7) {
                $form = new AddLpWidgetForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpWidgetInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 8) {
                $form = new AddLpDocumentForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpDocumentInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 9) {
                $form = new AddLpQuizForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpQuizInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }

            if ($postData['CONTTYPE_ID'] == 10) {
                $form = new AddLpQuizForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLpQuizInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 15) {
                $form = new AddLiveClassForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddLiveClassInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));

                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
            if ($postData['CONTTYPE_ID'] == 11) {
                $form = new AddAssignmentForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
                $formFilter = new AddAssignmentInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));

                return $this->submitLpFormData($request, $form, $formFilter, $viewModel, $contentId);
            }
        }
    }

    //@upload LP content
    function plUploadAction() {
        $chunkData = $_REQUEST;
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getFiles()->toArray();
        //echo '<pre>';print_r($postData);die;
        $config = $this->serviceLocator->get('config');
        if (!$config['liveurl']) {
            $ret = ['BACKING_FILE' => $postData['file']['name']];
            echo json_encode($ret);
            die;
        }
        
        $bucket = $config['s3bucket'];
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $path = $postData['file']['name'];
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $file = 'file_' . rand() . '_' . time() . '.' . $ext;
        if ($ext == 'zip') {
            $zip = new ZipArchive;
            $translator = $this->getServiceLocator()->get('translator');
            $retHtml = $this->CommonClass()->zipExtract($translator, $postData, $zip);
            $zipRandFolder = $retHtml['zipRandDir'];

            if ($config['AWS_ENABLE'] && $retHtml['htmlExist']) {
                $localPath = 'data/temp_upload/' . $zipRandFolder;
                //$client->uploadDirectory($localPath,$bucket.'/'.$zipRandFolder);
                $client->uploadDirectory($localPath, $bucket, "CONTENT/" . $zipRandFolder, array(
                    'params' => array('ACL' => 'public-read')
                ));
                /*                 * **************** Change ACL setting **************** */
                $this->CommonClass()->changeAclSetting("CONTENT/" . $zipRandFolder, $bucket, $client);
                /*                 * **************** Change ACL setting End **************** */
            }
            $this->CommonClass()->rrmdir('data/temp_upload/' . $zipRandFolder); //remove temp folder
            $ret = ['zipHtml' => $retHtml['zipHtml'], 'htmlExist' => $retHtml['htmlExist']];
            echo json_encode($ret);
            die;
        }
        //if AWS enable,use aws client object
        if ($config['AWS_ENABLE']) {
           $allow = array('pdf','doc','docx','xls','xlsx','ppt','pptx');
            if (in_array($ext, $allow)) {
                    $s3KeyArray = array(
                    'Bucket' => $bucket,
                    'Key' => "CONTENT/" . $file,
                    'SourceFile' => $postData['file']['tmp_name'],
                    'ACL' => 'public-read'
                );
                ($ext !== 'pdf') ?: $s3KeyArray['ContentType'] = 'application/pdf';
                $result = $client->putObject($s3KeyArray);
            } else {
                 if(!empty($_REQUEST['enrichment']) && $_REQUEST['enrichment']=='enrichment'){
                    $result = $client->putObject(array(
                        'Bucket' => $bucket,
                        'Key' => "CONTENT/" . $file,
                        'SourceFile' => $postData['file']['tmp_name'],
                        'ACL' => 'public-read'
                    ));
                }else{
                    $result = $client->putObject(array(
                        'Bucket' => $bucket,
                        'Key' => "CONTENT/" . $file,
                        'SourceFile' => $postData['file']['tmp_name'],
                        'ACL' => 'private'
                    ));
                }
            }
        }
        $ret = ['BACKING_FILE' => $file];
        echo json_encode($ret);
        die;
    }

    //@upload Assignment content
    function plAssignmentAction() {
        $chunkData = $_REQUEST;
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getFiles()->toArray();
        //echo '<pre>';print_r($postData);die;
        $config = $this->serviceLocator->get('config');
        $bucket = $config['s3bucket'];
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $path = $postData['file']['name'];
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $file = 'file_' . rand() . '_' . time() . '.' . $ext;

        $key = "CONTENT/" . $file;
        //if AWS enable,use aws client object
        if ($config['AWS_ENABLE']) {
            if ($ext == 'pdf') {
                $result = $client->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'SourceFile' => $postData['file']['tmp_name'],
                    'ContentType' => 'application/pdf',
                    'ACL' => 'public-read'
                ));
            } else {
                $result = $client->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'SourceFile' => $postData['file']['tmp_name'],
                    'ACL' => 'public-read'
                ));
            }
        }
        $ret = ['BACKING_FILE' => $file];
        echo json_encode($ret);
        die;
    }

    // Upload Profile Image
    function plUploadImageAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getFiles()->toArray();
        //echo '<pre>';print_r($postData);die;
        $config = $this->serviceLocator->get('config');
        $bucket = $config['s3bucket'];
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $filename = end(explode('/', $_POST['imagename']));
        $folder = (!empty($_POST['folder'])) ? $_POST['folder'] . "/" : "";
        $file = $folder . $filename;
        //if AWS enable,use aws client object
        if ($config['AWS_ENABLE']) {
            $sourceFile = getcwd() . '/public/upload/' . $filename;
            $result = $client->putObject(array(
                'Bucket' => $bucket,
                'Key' => $file,
                'SourceFile' => $sourceFile,
                'ACL' => 'public-read'
            ));
        }
        $targetDir = "public/upload/";
        $src = $targetDir . $filename;
        if ($config['liveurl']) {
            //unlink($src);
        }
        echo $file;
        die;
    }

    /**
      @LESSON PLAN
      ADD CONTENT ALL TABS FORM DATA PRCESSING
     */
    function submitLpFormData($request, $form, $formFilter, $viewModel, $contentId = null) {
        $translator = $this->getServiceLocator()->get('translator');
        $postData = $request->getPost()->toArray();
        //print_r($postData['topic']);die;
        $SUBJECT_ID = (!empty($postData['SUBJECT_ID'])) ? $postData['SUBJECT_ID'] : '';
        $catStr = (!empty($postData['TOPIC_ID'])) ? $postData['TOPIC_ID'] : '';
        $postData['learning_objective'] = !empty($postData['learning_objective']) ? $postData['learning_objective'] : "";
        // $catArr = (!empty($catStr)) ? explode(',', $catStr) : [];
        $this->initModelObject();
        $CONT_SRC = strip_tags($request->getPost()->get('CONT_SRC'), '<iframe>'); //iframe for embed
        if (empty($CONT_SRC)) {
            $request->getPost()->set('CONT_SRC', ''); //if cont_src fieled contain no char/string with blank tags like <br><p>
        }
        if (!empty($postData['zipradio'])) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
            $postData['BACKING_FILE'] = $postData['zipradio'];
            unset($postData['zipradio']);
            /*             * **************** Change ACL setting **************** */
            //$expBckFile = explode('/',$postData['BACKING_FILE']);
            //$this->changeAclSetting($expBckFile[0]);
            //$this->CommonClass()->changeAclSettingOfFile($postData['BACKING_FILE']);
            /*             * **************** Change ACL setting End **************** */
        }
        //if lp content edit,set required false for type file  [backing required false for IMAGE]
        if ((!empty($contentId) && (isset($postData['BACKING_FILE'])) || $postData['CONTTYPE_ID'] == 4)) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
        }
        if ((!empty($contentId) && (isset($postData['BACKING_FILE'])) || $postData['CONTTYPE_ID'] == 5)) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
        }
        if ((!empty($contentId) && (isset($postData['BACKING_FILE'])) || $postData['CONTTYPE_ID'] == 6)) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
        }
        if ((!empty($contentId) && (isset($postData['BACKING_FILE'])) || $postData['CONTTYPE_ID'] == 7)) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
        }
        if ((!empty($contentId) && (isset($postData['BACKING_FILE'])) || $postData['CONTTYPE_ID'] == 8)) {
            $formFilter->getInputFilter()->get('BACKING_FILE')->setRequired(false);
        }


        $form->setInputFilter($formFilter->getInputFilter());
        $form->setData($request->getPost());
        $postData['topic'] = isset($postData['topic']) ? $postData['topic'] : array();
        $err = 0;

        if (sizeof($postData['topic']) <= 0 || empty($postData['topic'])) {
            $err = 1;
            $result = ['result' => false, "target" => "#errordiv", 'innerhtml' => true, 'message' => $translator->translate("Please choose at least one topic")];
        }

//        if (sizeof($postData['learning_objective']) <= 0 || empty($postData['learning_objective']) && $err == 0) {
//            $err = 1;
//            $result = ['result' => false, "target" => "#errordivforlo", 'message' => $translator->translate("Please add learning objective")];
//        }

        if ($form->isValid() && !$err) {

            $finalDataPost['CONTTYPE_ID'] = $postData['CONTTYPE_ID'];
            $finalDataPost['LESSONPLAN_ID'] = $postData['LESSONPLAN_ID'];
            $finalDataPost['CONT_TITLE'] = $postData['CONT_TITLE'];
            $finalDataPost['CONT_DESC'] = (!empty($postData['CONT_DESC'])) ? $postData['CONT_DESC'] : "";
            $finalDataPost['CONT_SRC'] = isset($postData['CONT_SRC']) ? $postData['CONT_SRC'] : '';
            if (empty($contentId)) {
                $finalDataPost['CONT_ORDER'] = $this->db->getContentCountByLpId($postData['LESSONPLAN_ID']);
            }
            if (empty($contentId)) {
                /* if ($postData['CONTTYPE_ID'] == 8) {
                    $finalDataPost['FILE_UID'] = isset($postData['BACKING_FILE']) ? $postData['BACKING_FILE'] : '';
                } else { */
                    $finalDataPost['BACKING_FILE'] = isset($postData['BACKING_FILE']) ? $postData['BACKING_FILE'] : '';
//                }
                $finalDataPost['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                $result = $this->db->addLPContent($finalDataPost);
            } else {
                $finalDataPost['UPDATED_BY'] = $this->container->authDetail['USER_OID'];
                $result = $this->db->editLPContent($finalDataPost, $contentId);
                $result = $contentId;
            }

            if ($result) {
                // if ($postData['CONTTYPE_ID'] != 4) {
                $catArr = $postData['topic'];
                $this->db->deleteData('t_cm_cont_cat', ['CONT_ID' => $result]);
                for ($i = 0; $i < count($catArr); $i++) {
                    $InsData = [];
                    $InsData = ['CONT_ID' => $result, 'CAT_ID' => $catArr[$i]];
                    $this->db->insertData('t_cm_cont_cat', $InsData);
                }

                $catArrLo = $postData['learning_objective'];
                if (!empty($postData['learning_objective'])) {
                    $this->db->deleteData('t_cm_mgr_content_lo', ['CONT_ID' => $result]);
                    for ($i = 0; $i < count($catArrLo); $i++) {
                        $data = explode("_", $catArrLo[$i]);
                        // print_r($catArrLo[$i]);
                        $InsData = [];
                        $InsData = ['CONT_ID' => $result, 'TOPIC_ID' => $data[0], 'ST_LO_ID' => $data['1']];
                        $this->db->insertData('t_cm_mgr_content_lo', $InsData);
                    }
                }

                //   }
                $LpArray = $this->db->getLessonPlanById($finalDataPost['LESSONPLAN_ID']);
                if ($postData['CONTTYPE_ID'] == 11) {
                    //$quizId = $this->insertData($result); 
                    $redPath = $this->getRequest()->getBasePath() . '/assignment/create/' . $finalDataPost['LESSONPLAN_ID'] . '?second_id=' . $result . '&subject_id=' . $LpArray['SUBJECT_ID'];
                } else if ($postData['CONTTYPE_ID'] == 9) {
                    //$quizId = $this->insertData($result);
                    $redPath = $this->getRequest()->getBasePath() . '/create-quiz/index/' . $quizId;
                } else if ($postData['CONTTYPE_ID'] == 15) {
                    $redPath = $this->getRequest()->getBasePath() . '/grade/addclass/' . $result;
                } else {
                    //  $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $result;
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $result;
                    if ($postData['CONTTYPE_ID'] == 4) {
                        $result = $result . '?second_id=' . $SUBJECT_ID;
                        $redPath = $this->getRequest()->getBasePath() . '/grade/upload-image/' . $result;
                    }
                }
                $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'innerhtml' => true, 'redirectUrl' => $redPath];
            } else {
                $result = ['result' => false, 'message' => 'DB:Error'];
            }
        } else {
            if (sizeof($form->getMessages()) > 0) {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }
        }
        if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
            $viewModel = new JsonModel();
        }
        $viewModel->setVariables(['form' => $form, 'data' => $result]);
        return $viewModel;
    }

    public function editWidgetDataAction() {
        $contId = $this->params('id');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        //update data
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $translator = $this->getServiceLocator()->get('translator');
            if (!empty($postData['CONT_TITLE'])) {
                $this->initModelObject();
                //update content table first
                $finalDataPost['CONT_TITLE'] = $postData['CONT_TITLE'];
                $finalDataPost['CONT_DESC'] = $postData['CONT_DESC'];
                $finalDataPost['BACKING_FILE'] = $postData['BACKING_FILE'];
                $this->CommonClass()->changeAclSettingOfFile($postData['BACKING_FILE']);
                $finalDataPost['UPDATED_BY'] = $this->container->authDetail['USER_OID'];
                $result = $this->db->editLPContent($finalDataPost, $contId);
                //echo '<pre>';print_r($postData);die;
                $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan';
                $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'redirectUrl' => $redPath];
            } else {
                $formMsgArr['CONT_TITLE']['isEmpty'] = $translator->translate("Value is required and can't be empty");
                $result = ['result' => false, 'message' => $formMsgArr];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function editWidgetContentAction() {
        $contentId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        //check valid content id
        if (!empty($contentId)) {
            $this->initModelObject();
            $contData = $this->db->getContentByContentId($contentId, $this->container->authDetail['USER_OID']);
            if (empty($contData)) {
                return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
            }
        } else {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        $expBackFile = explode('/', $contData['BACKING_FILE']);
        $foldername = $expBackFile[0] . '/';
        $foldername = (!empty($_SESSION['PATH'][$_REQUEST['fld']])) ? $_SESSION['PATH'][$_REQUEST['fld']] : $foldername;
        $files_and_folder = $this->getAllHtmlFilesOfWidget($foldername);
        //echo "<pre>";  print_r($files_and_folder); die;
        $viewModel->setVariables([
            'lang' => $lang,
            'files_and_folder' => $files_and_folder,
            'foldername' => $foldername,
            'primary_file' => $contData['BACKING_FILE'],
            'contentId' => $contentId,
            'contData' => $contData,
            'baseFolder' => $expBackFile[0]
        ]);
        return $viewModel;
    }

    function getAllHtmlFilesOfWidget($foldername) {
        if (empty($foldername)) {
            return false;
        } else {
            $aws = $this->getServiceLocator()->get(Sdk::class);
            $client = $aws->createS3();
            $config = $this->serviceLocator->get('config');
            $bucket = $config['s3bucket'];
            $objects = $client->getIterator('ListObjects', array("Bucket" => $bucket, "Prefix" => $foldername));
            $htmlArr = array();
            $fullpath = array();
            $i = 0;
            $myarray = array();
            foreach ($objects as $object) {
                $path = str_replace($foldername, '', $object['Key']);
                $exp = explode(".", $path);
                $getExt = strtolower(end($exp));
                if ($getExt == 'html' || $getExt == 'htm') {
                    $htmlArr[] = $path;
                }
                $i++;
            }
            return $htmlArr;
        }
    }

    public function editWidgetAction() {
        $contentId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        //check valid content id
        if (!empty($contentId)) {
            $this->initModelObject();
            $contData = $this->db->getContentByContentId($contentId, $this->container->authDetail['USER_OID']);
            if (empty($contData)) {
                return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
            }
            $lpId = $this->db->getLessonplanIdByContentId($contentId);
            $lpDetail = $this->db->getLessonPlanDetail($lpId);
        } else {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        $expBackFile = explode('/', $contData['BACKING_FILE']);
        $foldername = $expBackFile[0] . '/';
        $foldername = (!empty($_SESSION['PATH'][$_REQUEST['fld']])) ? $_SESSION['PATH'][$_REQUEST['fld']] : $foldername;
        $files_and_folder = $this->getRootLevelFilesAndFolderWidget($foldername);
        //echo "<pre>";  print_r($files_and_folder); die;
        $lpImgForm = new AddLpImageForm();
        $viewModel->setVariables([
            'lang' => $lang,
            'files_and_folder' => $files_and_folder,
            'foldername' => $foldername,
            'primary_file' => $contData['BACKING_FILE'],
            'contentId' => $contentId,
            'baseFolder' => $expBackFile[0],
            'lpImgForm' => $lpImgForm,
            'lpDetail' => $lpDetail,
            'contData' => $contData
        ]);
        return $viewModel;
    }

    function setPrimaryAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $this->initModelObject();
            $postData = $request->getPost()->toArray();
            //echo '<pre>';print_r($postData);die;
            $success = $this->db->setAsPrimary($postData);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $success
            ));
            return $jsonModel;
        }
    }

    function getRootLevelFilesAndFolderWidget($foldername) {
        if (empty($foldername)) {
            return false;
        } else {
            $aws = $this->getServiceLocator()->get(Sdk::class);
            $client = $aws->createS3();
            $config = $this->serviceLocator->get('config');
            $bucket = $config['s3bucket'];
            $objects = $client->getIterator('ListObjects', array("Bucket" => $bucket, "Prefix" => $foldername));
            $root = array();
            $fullpath = array();
            $i = 0;
            $myarray = array();
            foreach ($objects as $object) {
                $path = str_replace($foldername, '', $object['Key']);
                //echo $path."<br/>";
                //$path =  $object['Key'];
                //echo $object['Key'] . "<br/>";
                $key = str_replace($foldername . '/', '', $object['Key']);
                //echo $key . "<br/>";
                //$key = $object['Key'];
                $f = explode('/', $path);
                // echo "<pre>"; echo $f[0]; echo "</pre>";
                if ($f[0] != "") {
                    if (!in_array($f[0], $myarray)) {
                        $root[$i]['name'] = $f[0];
                        $root[$i]['path'] = $key;
                        $root[$i]['size'] = $object['Size'];
                        $myarray[] = $f[0];
                    }
                } else {
                    if (!in_array($f[0], $myarray)) {
                        $root[$i]['name'] = $f[1];
                        $root[$i]['path'] = $key;
                        $root[$i]['size'] = $object['Size'];
                        $myarray[] = $f[0];
                    }
                }
                $i++;
            }
            //$rootPath = array_unique($root['path']);
            //$rootSize = array_unique($root['Size']);
            //$dirInfo = ['path'=>$rootPath,'size'=>$rootSize];
            return $root;
        }
    }

    public function lolAction() {
        $lessonPlanId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        //check valid lesson plan Id
        if (!empty($lessonPlanId)) {
            $this->initModelObject();
            $lpData = $this->db->getLessonPlanDetail($lessonPlanId);
            if (empty($lpData)) {
                return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
            }
        } else {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $adm = new AdministratorTable($dbadapter);
        $userCc = $adm->getCountryCodeByOrgId($this->container->authDetail['ORG_ID']);
        $countryData = $adm->getCountryData('A');
        $availableCont = $adm->getAllEnrCont();
        if (empty($_REQUEST['fld'])) {
            //	$_REQUEST['fld'] = base64_encode("LOL/".$userCc."/");
        }
        $foldername = (!empty($_SESSION['PATH'][$_REQUEST['fld']])) ? $_SESSION['PATH'][$_REQUEST['fld']] : 'LOL/' . $userCc . "/";
        $alloptions = 1;
        if ($foldername == 'LOL/') {
            $alloptions = 0;
        }
        $files_and_folder = $this->getRootLevelFilesAndFolder($foldername);
        //echo "<pre>";  print_r($files_and_folder); die;
        $viewModel->setVariables([
            'countryData' => $countryData,
            'lang' => $lang,
            'files_and_folder' => $files_and_folder,
            'availableCont' => $availableCont,
            'foldername' => $foldername,
            'alloptions' => $alloptions,
            'userCc' => $userCc,
            'lessonPlanId' => $lessonPlanId
        ]);
        return $viewModel;
    }

    function getRootLevelFilesAndFolder($foldername) {
        if (empty($foldername)) {
            return false;
        } else {
            // testing at local
            //return array('htmltest.html','file_1304572762_1474881874.mp3','file_1924258581_1474881373.mp4',' file_1931910666_1474888311.jpg','file_2097394003_1474885480.mp4','SK',"New" );
            $aws = $this->getServiceLocator()->get(Sdk::class);
            $client = $aws->createS3();
            $config = $this->serviceLocator->get('config');
            $bucket = $config['s3bucket'];
            $objects = $client->getIterator('ListObjects', array("Bucket" => $bucket, "Prefix" => $foldername));
            $root = array();
            $fullpath = array();
            $widget = array('html', 'html');
            $i = 0;
            $myarray = array();
            foreach ($objects as $object) {
                $path = str_replace($foldername, '', $object['Key']);
                //echo $object['Key'] . "<br/>";
                //echo $object['Key'] . "<br/>";
                $key = str_replace("LOL/", '', $object['Key']);
                ;
                $pos = strpos($path, 'wzip');
                $f = explode('/', $path);
                if ($pos === false) {
                    if ($f[0] != "") {
                        if (!in_array($f[0], $myarray)) {
                            $root[$i]['name'] = $f[0];
                            $root[$i]['path'] = $key;
                            $root[$i]['size'] = $object['Size'];
                            $myarray[] = $f[0];
                        }
                    } else {
                        if (!in_array($f[0], $myarray)) {
                            $root[$i]['name'] = $f[1];
                            $root[$i]['path'] = $key;
                            $root[$i]['size'] = $object['Size'];
                            $myarray[] = $f[0];
                        }
                    }
                } else {
                    //echo "<pre>"; print_r($f); echo "</pre>";
                    $last = end($f);
                    $extension = end(explode(".", $last));
                    if (in_array($extension, $widget)) {
                        //if(!in_array($f[0],$myarray)){
                        $root[$i]['name'] = $last;
                        $root[$i]['path'] = $key;
                        $root[$i]['size'] = $object['Size'];
                        $myarray[] = $f[0];
                        //}
                    }
                }
                $i++;
            }
            //$rootPath = array_unique($root['path']);
            //$rootSize = array_unique($root['Size']);
            //$dirInfo = ['path'=>$rootPath,'size'=>$rootSize];
            return $root;
        }
    }

    // return data for preview
    function previewAction() {
        $backingFile = (!empty($_GET['path'])) ? base64_decode($_GET['path']) : null;
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $adm = new AdministratorTable($dbadapter);
        $config = $this->serviceLocator->get('config');
        $data = array();
        if ($backingFile) {
            $dbData = $adm->checkEnrContByPath($backingFile);
            //echo "<pre>"; print_r($dbData); echo "</pre>";
            $newData = array();
            if (count($dbData)) {
                $getData = $dbData[0];
                //echo "<pre>"; print_r($getData); echo "</pre>";
                $viewHelperManager = $this->getServiceLocator()->get('ViewHelperManager');
                $s3Link = $viewHelperManager->get('s3Link');
                $public_path = str_replace('https', 'http', $s3Link("LOL/" . $getData['BACKING_FILE'], $config['s3bucket']));
                $newData['PUBLIC_URL'] = $public_path;
                $newData['ADDED_ON'] = date("d M, Y", strtotime($getData['CREATED_ON']));
                $filename = end(explode('/', $getData['BACKING_FILE']));
                $newData['TYPE'] = strtolower(end(explode('.', $filename)));
                $location = $getData['BACKING_FILE'];
                $newData['LOCATION'] = $location;
                $newData['TITLE'] = $getData['ENRICHCONT_TITLE'];
                $newData['EXTERNAL_ID'] = $getData['ENRICHCONT_ID'];
                $newData = json_encode($newData);
                print_r($newData);
                die;
            }
        }
        $data = json_encode($data);
        print_r($data);
    }

    /*     * **************    10 SEPT, 2016  START  **************************** */

    //upload multiple image for content
    function uploadImageAction() {
        $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
        $contId = $this->params('id');
        $tab = 'image-audio';
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $subject_id = (!empty($this->params()->fromQuery('second_id'))) ? $this->params()->fromQuery('second_id') : '';
        $navigationArr = $this->db->getCurriculumNavigation($subject_id, "topic");
        $navigation = (!empty($navigationArr)) ? $navigationArr['GRADE_NAME'] . ' / ' . $navigationArr['SUBJECT_NAME'] : '';
        $lpLinkForm = new AddLpImageForm();
        if (!empty($contId)) {

            $contData = $this->db->getContentByContentId($contId, $this->container->authDetail['USER_OID']);

            if (empty($contData)) {
                return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
            }
        } else {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        //$lpLinkForm->get('TOPIC_ID')->setValue($contData['TOPIC_IDS']);
        $contImgData = $this->db->getContentImages($contId);

        //echo '<pre>';print_r($contImgData);die;
        $viewModel->setVariables([
            'navigation' => $navigation,
            'lpForm' => $lpLinkForm,
            'contId' => $contId,
            'lang' => $lang,
            'contData' => $contData,
            'contImgData' => $contImgData,
            'tab' => $tab,
            'subject_id' => $subject_id
        ]);
        return $viewModel;
    }

    //edit multiple images
    function editImagesAction() {
        $contId = $this->params('id');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        //update data

        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $translator = $this->getServiceLocator()->get('translator');
            if (!empty($postData['CONT_TITLE'])) {
                if (!empty($postData['topic'])) {

                    $this->initModelObject();
                    //update content table first
                    //$catStr = (!empty($postData['TOPIC_ID'])) ? $postData['TOPIC_ID'] : '';
                    //$catArr = (!empty($catStr)) ? explode(',', $catStr) : [];
                    $catArr = $postData['topic'];
                    $finalDataPost['CONT_TITLE'] = $postData['CONT_TITLE'];
                    $finalDataPost['CONT_DESC'] = $postData['CONT_DESC'];
                    $finalDataPost['UPDATED_BY'] = $this->container->authDetail['USER_OID'];
                    $result = $this->db->editLPContent($finalDataPost, $contId);



                    $this->db->deleteData('t_cm_cont_cat', ['CONT_ID' => $contId]);
                    for ($i = 0; $i < count($catArr); $i++) {
                        $InsData = [];
                        $InsData = ['CONT_ID' => $contId, 'CAT_ID' => $catArr[$i]];
                        $this->db->insertData('t_cm_cont_cat', $InsData);
                    }

                    //echo '<pre>';print_r($postData);die;
                    //if image description
                    if (isset($postData['IMG_DESC'])) {
                        $countImg = count($postData['IMG_DESC']);
                        if ($countImg) {
                            for ($i = 0; $i < $countImg; $i++) {
                                $conImgId = $postData['CONT_IMG_ID'][$i];
                                $imgData['IMG_DESC'] = $postData['IMG_DESC'][$i];
                                $result = $this->db->editImageContent($imgData, $conImgId);
                            }
                        }
                    }
                    $lessonplan_id = $this->db->getLessonplanIdByContentId($contId);
                    $LpArray = $this->db->getLessonPlanById($lessonplan_id);
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $contId;
                    // $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $contId;
                    $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'redirectUrl' => $redPath];
                } else {
                    // $formMsgArr['topic']['isEmpty'] = $translator->translate("Value is required and can't be empty");
                    //$result = ['result' => false, 'message' => $formMsgArr];
                    $result = ['result' => false, "target" => "#errordiv", 'innerhtml' => true, 'message' => $translator->translate("Please choose at least one topic")];
                }
            } else {
                $formMsgArr['CONT_TITLE']['isEmpty'] = $translator->translate("Value is required and can't be empty");
                $result = ['result' => false, 'message' => $formMsgArr];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    //submit content for multi image upload
    function addLpImgAction() {
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        //echo '<pre>';print_r($postData);die;
        $this->initModelObject();
        if (!empty($postData['IMAGE'])) {
            $IMGES = substr($postData['IMAGE'], 1);
            $expImg = explode(',', $IMGES);
            //echo '<pre>';print_r($expImg);die;
            foreach ($expImg as $img) {
                $sendData['CONT_ID'] = $postData['CONT_ID'];
                $sendData['IMG_BACKING_FILE'] = $img;
                $this->db->saveMultipleImages($sendData);
            }
        }
        // $result=$postData['CONT_ID'].'?second_id='.$postData['SUBJECT_ID'];
        //              $redPath = $this->getRequest()->getBasePath() . '/grade/upload-image/' . $result;

        return $this->redirect()->toRoute('grade', array('action' => 'upload-image', 'id' => $postData['CONT_ID']), array('query' => array('second_id' => $postData['SUBJECT_ID'])));
    }

    /*     * **************    10 SEPT, 2016  END **************************** */

    //lesson plan detail page to show all types of file in player
    function lessonPlanDetailAction() {

        $translator = $this->getServiceLocator()->get('translator');
        $contentId = $this->params('id');
        $test_type = !empty($this->params()->fromQuery('test_type')) ? $this->params()->fromQuery('test_type') : '';
        $this->initModelObject();
        $ordId = $this->container->authDetail['ORG_ID'];
        $uId = $this->container->authDetail['USER_OID'];
        $isValidContId = $this->db->validContId($uId, $contentId);

        if (!$isValidContId && empty($test_type)) {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        //print_r($this->container->authDetail['ATB_AUTH_TOKEN']);die;
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $grade = new GradeTable($dbadapter);
        $displaybook = 0;
        if ($contentId && empty($test_type)) {
            $quizDetail = array();
            $getLessionId = $this->db->getLessonplanIdByContentId($contentId);
            $condArr['LP_ID'] = $getLessionId;
            $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);
            $lpData = $this->db->getLessonPlanData($condArr, $userIds);
            //  $lpData = $this->db->getLessonPlanData($condArr, $this->container->authDetail['ORG_ID']);
            $contentData = $this->db->getContentByContentId($contentId);
            //echo '<pre>';print_r($contentData);die;
            //8 sept, 2016 [if EXTERNAL_ID exist get content as per content type]
            $courseId = $grade->getCourseId($contentId);
            $GetLaunchUrl = $reportpage = "";
            if (!empty($courseId)) {

                $baseDirPath = getcwd() . '/library/';
                require_once($baseDirPath . "scorm/ScormEngineUtilities.php");
                require_once($baseDirPath . 'scorm/ScormEngineService.php');
                require_once($baseDirPath . 'scorm/Configuration.php');
                require_once($baseDirPath . 'scorm/ServiceRequest.php');
                require_once($baseDirPath . 'scorm/ReportingService.php');
                $config = $this->serviceLocator->get('config');
                $ServiceUrl = $config['scorm_serviceurl'];
                $SecretKey = $config['scorm_secretkey'];
                $AppId = $config['scorm_appid'];
                $Origin = ScormEngineUtilities::getCanonicalOriginString('Piron', 'Test', 'Version 2.0');
                $ScormService = new ScormEngineService($ServiceUrl, $AppId, $SecretKey, $Origin);
                $regService = $ScormService->getRegistrationService();
                $status = "Uncomplete";
                $REG_ID = $grade->checkScormUserRegistration($courseId, $this->container->authDetail['USER_OID']);
                if (empty($REG_ID)) {
                    $regId = uniqid(rand(), true);
                    $learnerId = $this->container->authDetail['EMAIL_ID'];
                    $learnerFirstName = $this->container->authDetail['FIRST_NAME'];
                    $learnerLastName = $this->container->authDetail['LAST_NAME'];
                    // Save on scorm
                    $response = $regService->CreateRegistration($regId, $courseId, $learnerId, $learnerFirstName, $learnerLastName);
                    // Saving data into tables
                    $regArr['SCORM_COURSE_ID'] = $courseId;
                    $regArr['USER_OID'] = $this->container->authDetail['USER_OID'];
                    $regArr['REG_ID'] = $regId;
                    $grade->saveUserScormRegistration($regArr);
                    $REG_ID = $regId;
                }
                //echo "$REG_ID, $courseId <br/>" ;
                $conf = new Configuration($config['scorm_serviceurl'], $AppId, $SecretKey);
                $srvc = new ReportingService($conf);
                $learnerId = $this->container->authDetail['EMAIL_ID'];
                $homePage = "/Reportage/reportage.php?appId=$AppId";
                $learnerPage = $homePage . "&courseId=$courseId&learnerId=$learnerId";
                $reportageAuth = $srvc->GetReportageAuth('NONAV', false);
                $reportpage = $srvc->GetReportUrl($reportageAuth, $learnerPage);
                $GetLaunchUrl = $regService->GetLaunchUrl($REG_ID, $reportpage);
                /*
                  $allResults = $regService->GetLaunchHistory($REG_ID);
                  if(count($allResults)){
                  foreach($allResults as $result){
                  if($result->getCompletion()=='complete' && $result->getSatisfaction()=='passed'){
                  $status = "Completed";
                  break;
                  }
                  }
                  } */
            }
            if (!empty($contentData['EXTERNAL_ID'])) {
                if ($contentData['CONTTYPE_ID'] == '13') {
                    $grade = new GradeTable($dbadapter);
                    $contDataTemp = $contentData;
                    $bookData = $grade->getBookDetailByBookId($contentData['EXTERNAL_ID']);
                    //echo '<pre>';print_r($contentData);die;
                    //$contentData['LESSONPLAN_ID'] = $contDataTemp['LESSONPLAN_ID'];
                    //$contentData['CONT_ID'] = $contDataTemp['CONT_ID'];
                    //$contentData['CONT_TYPE'] = $this->db->getContentTypeById($contentData['CONTTYPE_ID']);//ENRICHMENT : [VIDEO/AUDIO/WIDGET/DOCUMENT]
                    //$contentData['CONT_ID'] = $contentData['ENRICHCONT_ID'];
                    $contentData['CONT_TITLE'] = $bookData['BOOK_NAME'];
                    $contentData['BOOK_HASH'] = $bookData['BOOK_HASH'];
                    $contentData['CONT_DESC'] = $bookData['BOOK_DESCRIPTION'];
                    $contentData['BACKING_FILE'] = $bookData['BOOK_BACKING_FILE'];
                    //print_r($contentData);die;
                } else {
                    $adm = new AdministratorTable($dbadapter);
                    $contDataTemp = $contentData;
                    $contentData = $adm->getEnrichmentContentById($contentData['EXTERNAL_ID']);
                    $contentData['BACKING_FILE'] = 'LOL/' . $contentData['BACKING_FILE'];
                    //echo '<pre>';print_r($contentData);die;
                    $contentData['LESSONPLAN_ID'] = $contDataTemp['LESSONPLAN_ID'];
                    $contentData['CONT_ID'] = $contDataTemp['CONT_ID'];
                    $contentData['CONT_TYPE'] = $this->db->getContentTypeById($contentData['CONTTYPE_ID']); //ENRICHMENT : [VIDEO/AUDIO/WIDGET/DOCUMENT]
                    //$contentData['CONT_ID'] = $contentData['ENRICHCONT_ID'];
                    $contentData['CONT_TITLE'] = $contentData['ENRICHCONT_TITLE'];
                    $contentData['CONT_DESC'] = $contentData['ENRICHCONT_DESC'];
                }
            }
            /*             * ******************************** Acl Checking Start *********************************** */
            $aclCheck = 0;
            if (!empty($contentData['EXTERNAL_ID'])) {
                if ($contentData['CONTTYPE_ID'] == '13') {
                    $aclCheck = 1;
                }
            }
            $register = 0;


            $liveClassUrl = "";
            if ($contentData["CONTTYPE_ID"] == 15) {
                $liveClassUrl = $this->db->getLiveClassUrlByContId($this->container->authDetail["UT_ID"], $contentData["CONT_ID"]);
                //$liveClassUrl = "https://live.wiziq.com/aliveext/LoginToSession.aspx?SessionCode=9sbzXtdmlusyyNLYRsnIhA%3d%3d";
            }
        } else if (!empty($test_type) && ($test_type == 'ST' || $test_type == 'FT')) {
            $lpData = [];
            $quizDetail = [];
            $contentData = [];
            $displaybook = 0;
            $GetLaunchUrl = '';
            $liveClassUrl = '';
        } else {
            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
        }
        if (!empty($contentData)) {
            $param = [
                'title' => $contentData['CONT_TITLE'] . " - " . $translator->translate("Kalemon"),
                'keywords' => $contentData['CONT_TITLE'],
                'description' => $contentData['CONT_TITLE']
            ];
        } else {
            $param = ['title' => '', 'keywords' => '', 'description' => ''];
        }
        $this->CommonClass()->setMetaData($this, $param);
        $this->CommonClass()->setCustomLayout($this, 'lpLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setVariables([
            'lpData' => $lpData,
            "contentId" => $contentId,
            "contentData" => $contentData,
            'authDetail' => $this->container->authDetail,
            'quizDetail' => $quizDetail,
            'displaybook' => $displaybook,
            'title' => "SK",
            'keywords' => "SK",
            'description' => "SK",
            'GetLaunchUrl' => $GetLaunchUrl,
            'liveClassUrl' => $liveClassUrl,
            'test_type' => $test_type
        ]);
        return $viewModel;
    }

    /**
      @lesson plan add content
      get meta Info by URL on lesson plan add content popup
     */
    function extractUrlAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postData = $request->getPost()->toArray();
            $translator = $this->getServiceLocator()->get('translator');
            $output = '';

            $configbookUrl = str_replace("www.", "", strtolower($postData['configbookUrl']));
            //  echo "\n";
            $urlStr = str_replace("www.", "", strtolower($postData["url"]));
            // echo "\n";
            $numaricdata = trim(end(explode($configbookUrl, $urlStr)));
            //echo "\n";
            $makeurl = str_replace($numaricdata, "", $urlStr);

            // echo $makeurl."!=.".$configbookUrl;
            $data = array();

            if ($data == 0 || !is_numeric($numaricdata)) {
                $msg = $translator->translate("Invalid Url");
                $output = '<div class="alert alert-danger no-border"><button type="button" class="close" data-dismiss="alert"><span class="sr-only">Close</span></button><span class="text-semibold">' . $msg . '</span></div>';
                $jsonModel = new JsonModel();
                $jsonModel->setVariables(array(
                    'result' => $output,
                    'error' => 1,
                ));
                return $jsonModel;
            }
            //print_r($postData);die;
            $postData["url"] = str_replace("www.", "", strtolower($postData["url"]));
            $parsed = parse_url($postData["url"]);
            if (empty($parsed['scheme'])) {
                $urlStr = 'http://' . ltrim($postData["url"], '/');
            }
            $header = @get_headers($urlStr, 1);
            if (isset($header['X-Frame-Options']) && (stripos($header['X-Frame-Options'], 'SAMEORIGIN') !== false || stripos($header['X-Frame-Options'], 'deny') !== false)) {
                $msg = $translator->translate("This url could not be open inside iframe");
                $output = '<div>' . $msg . '</div>';
                $jsonModel = new JsonModel();
                $jsonModel->setVariables(array(
                    'result' => $output
                ));
                return $jsonModel;
            }
            if (filter_var($postData["url"], FILTER_VALIDATE_URL)) {
                $output = $this->CommonClass()->getExtractUrlData($postData);
            }
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $output
            ));
            return $jsonModel;
        }
    }

    //subject list subject as per grade selected
    function listSubjectAction() {
        $gradeId = $this->params('id');
        if (empty($gradeId)) {
            return $this->redirect()->toRoute('grade');
        }
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $subjects = $this->db->getSubjects($gradeId);
        $gradeDetail = $this->db->getGradeDetails($gradeId);
        $batchName = $this->db->getBatchName($gradeDetail['BATCH_ID'], $this->container->authDetail['ORG_ID']);
        if (empty($batchName)) {
            return $this->redirect()->toRoute('grade', array('action' => 'list-batch'));
        }
        $viewModel->setVariables(['subjects' => $subjects, 'gradeId' => $gradeId, 'gradeDetail' => $gradeDetail, 'batchName' => $batchName]);
        return $viewModel;
    }

    //set variable for popup Subject
    function setModelVarForPopupSubject($viewModel, $requestData) {
        $gradeId = $requestData['gradeId'];
        $id = $subjectName = $teacherId = '';
        if (!empty($requestData['id'])) {
            $id = $requestData['id'];
            $this->initModelObject();
            $subjectData = $this->db->getSubjectDetailById($id);
            $subjectName = $subjectData['SUBJECT_NAME'];
            $teacherId = $subjectData['TEACHER_ID'];
        }
        $form = new SubjectForm($this->getAdapter(), $gradeId, $this->container->authDetail['ORG_ID']);
        $viewModel->setVariables(array('form' => $form, 'gradeId' => $gradeId, 'id' => $id, 'subjectName' => $subjectName, 'teacherId' => $teacherId));
        return $viewModel;
    }

    //function to add subject
    function addSubjectAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $gradeId = $postData['GRADE_ID'];
            $addForm = new SubjectForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $gradeId, $this->container->authDetail['ORG_ID']);
            $filterObj = new SubjectInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($filterObj->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $this->initModelObject();
                if (empty($postData['SUBJECT_ID'])) {
                    unset($postData['SUBJECT_ID']);
                    $result = $this->db->addSubject($postData);
                } else {
                    $result = $this->db->editSubject($postData);
                }
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-subject/' . $gradeId;
                    $result = ['result' => true, 'message' => 'Subject has been saved successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    /*     * ********************* NEW *********************** */

    /**
      @Display syllabus tree with action [Edit/Delete]
     */
    function printCatTreeEdit($subjectId) {
        $translator = $this->getServiceLocator()->get('translator');
        $this->initModelObject();
        $tree = $this->db->getCategoryTreeWithOutDepth($subjectId);
        $result = '';
        $currDepth = 0;
        $lastNodeIndex = count($tree) - 1;
        $addTopicIconClass = '';
        if (count($tree)) {
            foreach ($tree as $index => $currNode) {
                if ($currNode['DEPTH'] > $currDepth || $index == 0) {
                    $result .= '<ul>';
                }
                if ($currNode['DEPTH'] < $currDepth) {
                    $result .= str_repeat('</ul></li>', $currDepth - $currNode['DEPTH']);
                }
                if ($currNode['CAT_FLAG'] == 'T') {
                    $addTopicIconClass = 'lesion-plan';
                } else {
                    $addTopicIconClass = '';
                }
                $t = ($index == 0) ? 1 : 2;
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    //popup_delete_syllabus
                    $deleteUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'popup_delete_syllabus', 'router' => 'grade', 'subjectId' => $subjectId, 'parentCat' => $currNode['CAT_ID'])));
                    $editUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'add-syllabus', 'router' => 'grade', 'subjectId' => $subjectId, 'parentCat' => $currNode['CAT_ID'], 'mode' => 'edit')));
                    /*
                      // Will be use later
                      $options = '<div class="media-right media-middle">
                      <ul class="icons-list text-nowrap">
                      <li>sasas
                      <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="icon-more2"></i></a>
                      <ul class="dropdown-menu dropdown-menu-right">
                      <li>sasasssss<a href="'.$editUrl.'"><i class="  icon-key pull-right"></i>'.$translator->translate("Edit").'</a></li>
                      <li><a href="#" data-title="Delete Grade" data-toggle="lightbox" data-remote="'.$deleteUrl.'"><i class="icon-user-cancel pull-right"></i>'.$translator->translate("Delete").'</a></li>
                      </ul>
                      </li>
                      </ul>
                      </div>';
                     */
                    $result .= '<li class="expanded level ' . $addTopicIconClass . '">' . $currNode['CAT_NAME'] . '<div class="cat-space-2"><a href="#" class="label bg-info-400 mr-5 ml-10" data-title="' . $translator->translate("Edit Syllabus") . '"  data-toggle="lightbox" data-remote="' . $editUrl . '">' . $translator->translate("Edit") . '</a><a href="#" data-title="' . $translator->translate("Delete Syllabus") . '" class="label bg-danger-400" data-toggle="lightbox" data-remote="' . $deleteUrl . '">' . $translator->translate("Delete") . '</a> </div>';
                } else {
                    $deleteUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'popup_delete_syllabus', 'router' => 'grade', 'subjectId' => $subjectId, 'parentCat' => $currNode['CAT_ID'])));
                    $editUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'add-syllabus', 'router' => 'grade', 'subjectId' => $subjectId, 'parentCat' => $currNode['CAT_ID'], 'mode' => 'edit')));
                    $result .= '<li class="expanded level ' . $addTopicIconClass . '">' . $currNode['CAT_NAME'] . '<div class="cat-space-2"><a href="#" class="label bg-info-400 mr-5 ml-10" data-title="' . $translator->translate("Edit Syllabus") . '"  data-toggle="lightbox" data-remote="' . $editUrl . '">' . $translator->translate("Edit") . '</a><a href="#" class="label bg-danger-400" data-title="' . $translator->translate("Delete Syllabus") . '" data-toggle="lightbox" data-remote="' . $deleteUrl . '">' . $translator->translate("Delete") . '</a> </div>';
                }
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $result .= '</li>'; // If not, close the <li>
                }
                $currDepth = $currNode['DEPTH'];
                if ($index == $lastNodeIndex) {
                    // $result .= '<ul></ul>' . str_repeat('</li></ul>', $currDepth);
                    $result .= str_repeat('</li></ul>', $currDepth);
                }
            }
        }
        return $result;
    }

    //list syllabus category
    public function listSyllabusAction() {
        $subjectId = $this->params('id');
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $this->initModelObject();
        $catTreeWithHtml = $this->printCatTreeEdit($subjectId);
        $subjectDetail = $this->db->getSubjectDetailById($subjectId);
        $gradeDetail = $this->db->getGradeDetails($subjectDetail['GRADE_ID']);
        $batchName = $this->db->getBatchName($gradeDetail['BATCH_ID'], $this->container->authDetail['ORG_ID']);
        if (empty($batchName)) {
            return $this->redirect()->toRoute('grade', array('action' => 'list-batch'));
        }
        $viewModel->setVariables(['subjectId' => $subjectId, 'parentCat' => '', 'catTreeWithHtml' => $catTreeWithHtml, 'gradeDetail' => $gradeDetail, 'subjectDetail' => $subjectDetail, 'batchName' => $batchName]);
        return $viewModel;
    }

    /**
      @To show category/syllabus tree [popup]
     */
    function printCatTree($subjectId) {
        $this->initModelObject();
        $tree = $this->db->getCategoryTreeWithOutDepth($subjectId);
        $result = '';
        $currDepth = 0;
        $lastNodeIndex = count($tree) - 1;
        $result = "";
        if (count($tree)) {
            foreach ($tree as $index => $currNode) {
                if ($currNode['DEPTH'] > $currDepth || $index == 0) {
                    $result .= '<ul>';
                }
                if ($currNode['DEPTH'] < $currDepth) {
                    $result .= str_repeat('</ul></li>', $currDepth - $currNode['DEPTH']);
                }
                if ($currNode['CAT_FLAG'] == 'T') {
                    $addTopicIconClass = 'lesion-plan';
                } else {
                    $addTopicIconClass = '';
                }
                $t = ($index == 0) ? 1 : 2;
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $result .= '<li class="expanded level ' . $addTopicIconClass . '">' . '<a href="javascript:void(0);">' . $currNode['CAT_NAME'] . ' </a>';
                } else {
                    $result .= '<li class="expanded level ' . $addTopicIconClass . '">' . '<a href="javascript:void(0);">' . $currNode['CAT_NAME'] . ' </a>';
                }
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $result .= '</li>'; // If not, close the <li>
                }
                $currDepth = $currNode['DEPTH'];
                if ($index == $lastNodeIndex) {
                    // $result .= '<ul></ul>' . str_repeat('</li></ul>', $currDepth);
                    $result .= str_repeat('</li></ul>', $currDepth);
                }
            }
        }
        return $result;
    }

    /**
      @To pick category/syllabus tree [popup]
     */
    function pickCatTree($subjectId) {
        $translator = $this->getServiceLocator()->get('translator');
        $this->initModelObject();
        $tree = $this->db->getCategoryTreeWithOutDepth($subjectId);
        $result = '';
        $currDepth = 0;
        $lastNodeIndex = count($tree) - 1;
        if (!empty($tree)) {
            foreach ($tree as $index => $currNode) {
                if ($currNode['DEPTH'] > $currDepth || $index == 0) {
                    $result .= '<ul>';
                }
                if ($currNode['DEPTH'] < $currDepth) {
                    $result .= str_repeat('</ul></li>', $currDepth - $currNode['DEPTH']);
                }
                $t = ($index == 0) ? 1 : 2;
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $remoteUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'add-syllabus', subjectId => $subjectId, 'parentCat' => $currNode['CAT_ID'], 'router' => 'grade')));
                    $result .= '<li class="expanded level">' . $currNode['CAT_NAME'] . '<div class="pick_parent cat-space-2"><a href="#" class="label bg-info-400 mr-5 ml-10" data-title="Add Syllabus" data-rel="add_syllabus"  data-toggle="lightbox" data-remote="' . $remoteUrl . '"  data-dismiss="modal"> <span class="pic-tree-section">' . $translator->translate("Pick") . '</span></a></div>';
                } else {
                    $remoteUrl = $this->getServiceLocator()->get('ViewHelperManager')->get('url')->__invoke('grade', array('action' => 'openPopup'), array('query' => array('module' => 'secure', 'view' => 'grade', 'file' => 'add-syllabus', subjectId => $subjectId, 'parentCat' => $currNode['CAT_ID'], 'router' => 'grade')));
                    $result .= '<li class="expanded level">' . $currNode['CAT_NAME'] . '<div class="pick_parent cat-space-2"> <a href="#" data-title="Add Syllabus" class="label bg-info-400 mr-5 ml-10" data-rel="add_syllabus"  data-toggle="lightbox" data-remote="' . $remoteUrl . '" data-dismiss="modal"> <span class="pic-tree-section">' . $translator->translate("Pick") . '</span></a>  </div>';
                }
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $result .= '</li>'; // If not, close the <li>
                }
                $currDepth = $currNode['DEPTH'];
                if ($index == $lastNodeIndex) {
                    // $result .= '<ul></ul>' . str_repeat('</li></ul>', $currDepth);
                    $result .= str_repeat('</li></ul>', $currDepth);
                }
            }
        }
        return $result;
    }

    /**
      @ Change Parent Category
     */
    function changeParent($subjectId) {
        $translator = $this->getServiceLocator()->get('translator');
        $this->initModelObject();
        $tree = $this->db->getCategoryTreeWithOutDepth($subjectId, 'T');
        $result = '';
        $currDepth = 0;
        $lastNodeIndex = count($tree) - 1;
        if (!empty($tree)) {
            foreach ($tree as $index => $currNode) {
                if ($currNode['DEPTH'] > $currDepth || $index == 0) {
                    $result .= '<ul>';
                }
                if ($currNode['DEPTH'] < $currDepth) {
                    $result .= str_repeat('</ul></li>', $currDepth - $currNode['DEPTH']);
                }
                $t = ($index == 0) ? 1 : 2;
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    //$result .= '<li class="expanded level"><p class="pick_parent cat-space-2" id="cat-'.$currNode['CAT_ID'].'">' . $currNode['CAT_NAME']."</p>";
                    $result .= '<li class="expanded level cat-' . $currNode['CAT_ID'] . '" id="id-' . $currNode['CAT_ID'] . '">' . $currNode['CAT_NAME'] . '<p style="display:none;">' . $currNode['CAT_ID'] . '</p>';
                } else {
                    //$result .= '<li class="expanded level"><p class="pick_parent cat-space-2" id="cat-'.$currNode['CAT_ID'].'">' .  $currNode['CAT_NAME']."</p>";
                    $result .= '<li class="expanded level cat-' . $currNode['CAT_ID'] . '" id="id-' . $currNode['CAT_ID'] . '">' . $currNode['CAT_NAME'] . '<p style="display:none;">' . $currNode['CAT_ID'] . '</p>';
                }
                if ($index != $lastNodeIndex && $tree[$index + 1]['DEPTH'] <= $tree[$index]['DEPTH']) {
                    $result .= '</li>'; // If not, close the <li>
                }
                $currDepth = $currNode['DEPTH'];
                if ($index == $lastNodeIndex) {
                    $result .= str_repeat('</li></ul>', $currDepth);
                }
            }
        }
        return $result;
    }

    //save category : to add catgory
    function saveSyllabusAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $addForm = new AddSyllabusForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $postData['subjectId'], $postData['parentCat'], $postData['catFlag']);
            $catgFilter = new AddSyllabusInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $addForm->setInputFilter($catgFilter->getInputFilter());
            $addForm->setData($request->getPost());
            if ($addForm->isValid()) {
                $this->initModelObject();
                if (!isset($postData['position'])) {
                    //update syllabus
                    $result = $this->db->updateCategory($postData);
                } else {
                    //insert syllabus
                    $result = $this->db->insertNewCategory($postData);
                }
                $redPath = $this->getRequest()->getBasePath();
                if ($result) {
                    $redPath = $redPath . '/grade/list-syllabus/' . $postData['subjectId'];
                    $result = ['result' => true, 'message' => 'Data has been saved successfully', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $result = ['result' => false, 'message' => $addForm->getMessages()];
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //get child catgs
    function childGradeAction() {
        $this->initModelObject();
        $subjectId = (!empty($_POST['subjectId'])) ? $_POST['subjectId'] : 0;
        $parentCat = (!empty($_POST['parentCat'])) ? $_POST['parentCat'] : 0;
        //$catFlag = (!empty($_POST['catFlag']))?$_POST['catFlag']:'M';
        if (!$parentCat || $parentCat == 'NaN') {
            $getafterCatArray = $this->db->getAllRootLevelCategory($subjectId);
        } else {
            $getafterCatArray = $this->db->getAllChildCatByParent($subjectId, $parentCat);
        }
        if (count($getafterCatArray)) {
            ?>
            <select data-width="100%" class="form-control-static form-control mt-10" name="afterWhich">
                <?php foreach ($getafterCatArray as $key => $val) { ?>
                    <option value="<?php echo $val['CAT_ID']; ?>"><?php echo $val['CAT_NAME']; ?></option>
                    <?php
                }
                ?>
            </select>
            <?php
        }
        die;
    }

    //get child catgs
    public function lessonplanbyClassAction() {
        $this->initModelObject();
        $classId = (!empty($_POST['classid'])) ? $_POST['classid'] : null;
        $subject_id = (!empty($_POST['subject_id'])) ? $_POST['subject_id'] : null;
        $lessionPlan = $this->db->getAllLessonPlanByClassAndSubject($classId, $subject_id);
        if (count($lessionPlan)) {
            ?>
            <select data-width="100%" class="form-control-static form-control mt-10" name="LP_POSITION">
                <?php foreach ($lessionPlan as $key => $val) { ?>
                    <option value="<?php echo $val['LESSONPLAN_ID']; ?>"><?php echo $val['LP_NAME']; ?></option>
                    <?php
                }
                ?>
            </select>
            <?php
        }
        die;
    }

    public function getSubjectAction() {
        $garde_id = $this->params('id');
        $dbAdapter = $this->getAdapter();
        $this->db = new GradeTable($dbAdapter);
        $teacher = null;
        if ($this->container->authDetail['UT_ID'] == '2') {
            $teacher = $this->container->authDetail['USER_OID'];
        }
        $grade = $this->db->getSubjectByGrade($garde_id, $teacher);
        $translator = $this->getServiceLocator()->get('translator');
        $sel_subject = $translator->translate('Select Subject');
        $str = '<option value="0" >' . $sel_subject . '</option>';
        if (count($grade)) {
            foreach ($grade as $val) {
                $str .= '<option value="' . $val['SUBJECT_ID'] . '">' . $val['SUBJECT_NAME'] . '</option>';
            }
        }
        echo $str;
        die;
    }

    public function getTopicAction() {
        $subject_id = $this->params('id');
        $dbAdapter = $this->getAdapter();
        $this->db = new GradeTable($dbAdapter);
        $topic = []; //$this->db->getTopicBySubject($subject_id);
        $translator = $this->getServiceLocator()->get('translator');
        $sel = $translator->translate('Select Topic');
        $str = '<option value="0" >' . $sel . '</option>';
        if (count($topic)) {
            foreach ($topic as $val) {
                $str .= '<option value="' . $val['CAT_ID'] . '">' . $val['CAT_NAME'] . '</option>';
            }
        }
        echo $str;
        die;
    }

    public function getClassAction() {
        $postData = $this->getRequest()->getPost()->toArray();
        $id = (!empty($postData['student_id'])) ? $postData['student_id'] : "";
        $studentId = (!empty($id)) ? $id : $this->container->authDetail['USER_OID'];

        $grade_id = $this->params('id');
        $dbAdapter = $this->getAdapter();
        $this->db = new GradeTable($dbAdapter);
        $teacher = null;
        if ($this->container->authDetail['UT_ID'] == '1' || $this->container->authDetail['UT_ID'] == '3') {
            $subject = $this->db->getAllSubjectListOfUser($studentId, $grade_id);
        } else {
            if ($this->container->authDetail['UT_ID'] == '2') {
                $teacher = $studentId;
            }
            $subject = $this->db->getSubjectByGrade($grade_id, $teacher);
        }
        $translator = $this->getServiceLocator()->get('translator');
        $sel = $translator->translate('Select Subject');
        $str = '<option value="" >' . $sel . '</option>';
        if (!$grade_id) {
            echo $str;
            die;
        }
        if (count($subject)) {
            foreach ($subject as $val) {
                $str .= '<option value="' . $val['SUBJECT_ID'] . '">' . $val['SUBJECT_NAME'] . '</option>';
            }
        }
        echo $str;
        die;
    }

    function appendPrerequisiteAction() {
        $this->initModelObject();
        $classId = (!empty($_POST['classid'])) ? $_POST['classid'] : null;
        $subject_id = (!empty($_POST['subject_id'])) ? $_POST['subject_id'] : null;
        $lessionPlan = $this->db->getAllLessonPlanByClassAndSubject($classId, $subject_id);
        $translator = $this->getServiceLocator()->get('translator');
        $sel = $translator->translate('Select Lesson Plan');
        if (count($lessionPlan)) {
            ?>
            <select data-width="100%" class="form-control-static form-control mt-10" name="prerequisite[]">
                <option value=""><?php echo $sel; ?></option>
                <?php foreach ($lessionPlan as $key => $val) { ?>
                    <option value="<?php echo $val['LESSONPLAN_ID']; ?>"><?php echo $val['LP_NAME']; ?></option>
                    <?php
                }
                ?>
            </select>
            <?php
        }
        die;
    }

    public function removeEnrollmentAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $this->initModelObject();
            $postData = $this->getRequest()->getPost()->toArray();
            $success = $this->db->removeUserEnrollment($postData['enrId']);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => $success
            ));
            return $jsonModel;
        }
    }

    /**
     * @desc used of this function for insert data in quiz table
     * @param int $CONT_ID
     */
    private function insertData($CONT_ID) {
        $table = $this->initTable('Secure\Model\Quiz\CreateQuizTable');
        $createdBy = $this->container->authDetail['USER_OID'];
        $insertData = [
            'CONT_ID' => $CONT_ID,
            'STATUS' => 'I',
            'CREATED_BY' => $createdBy,
            'CREATED_ON' => date('Y-m-d H:i:s'),
            'PUBLISH' => 'N'
        ];
        return $table->insertData($insertData);
    }

    /**
     * @desc used of this fuction for initialize for table objet
     * @param string $table
     */
    public function initTable($table) {
        return new $table($this->getAdapter());
    }

    function pullGradeAction() {
        // echo ('ddd'); die;
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        $this->initModelObject();
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $curriculum = new CurriculumTable($dbadapter);
        $translator = $this->getServiceLocator()->get('translator');
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $org_id = $this->container->authDetail['ORG_ID'];
            $postData = $request->getPost()->toArray();
           // print_r($postData);
            $error = 0;
            $grd = array();
            $gardes = "";
            if (empty($postData['ADM_STANDARD_ID'])) {
                $error = 1;
            }
            if ($error) {
                $result = ['result' => false, 'message' => $translator->translate('Please select Standard'), 'target' => '#dispErrMsgPull'];
            } else {
                $Standard = $curriculum->getStandardDetail($postData['ADM_STANDARD_ID']);
                //$batch_id = $postData['batch_id'];
            }
            if (count($Standard) && $error == 0) {
                $standardarray = array();
                $standardarray['STANDARD_NAME'] = $Standard['STANDARD_NAME'];
                $standardarray['COUNTRY_ID'] = $Standard['COUNTRY_ID'];
                $standardarray['ORG_ID'] = $org_id;
                $standardarray['STATUS'] = $Standard['STATUS'];
                $standardarray['ADM_REF_ID'] = $Standard['STANDARD_ID'];
                $standardarray['CREATED_ON'] = date("Y-m-d H:i:s");
                $standardarray['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                
                
                $new_Standard_id = $this->db->savePullStandard($standardarray);
                
                 //get grade deatil 
                $grd = $curriculum->getGradeDetailsForImport($postData['ADM_STANDARD_ID']);
           // print_r($grd); 
                if (count($grd) > 0 && $new_Standard_id) {
                    foreach ($grd as $grade) {
                        $gradearray = array();
                        $gradearray['ADM_REF_ID'] = $grade['GRADE_ID'];
                        $gradearray['ORG_ID'] = $org_id;
                        $gradearray['STANDARD_ID'] = $new_Standard_id;
                        $gradearray['GRADE_NAME'] = $grade['GRADE_NAME'];
                        $gradearray['GRADE_ORDER'] = $grade['GRADE_ORDER'];
                        $gradearray['GRADE_CODE'] = $grade['GRADE_CODE'];
                        $gradearray['GRADE_DESC'] = $grade['GRADE_DESC'];
                        $gradearray['CREATED_ON'] = date("Y-m-d H:i:s");
                        $gradearray['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                        //print_r($gradearray);die;
                        $new_grade_id = $this->db->savePullGrade($gradearray);
                        //==================================
                        // insert grade data end
                        $subjects = $curriculum->getSubjectsForImport($grade['GRADE_ID']);
                        if (count($subjects) && $new_grade_id) {
                            foreach ($subjects as $sub) {
                                // Insert Subject data Start
                                $subjectArray = array();
                                $subjectArray['ADM_REF_ID'] =$sub['SUBJECT_ID'];
                                $subjectArray['GRADE_ID'] = $new_grade_id;
                                $subjectArray['SUBJECT_NAME'] = $sub['SUBJECT_NAME'];
                                
                                //$new_subject_id = 1;
                               $new_subject_id = $this->db->savePullSubject($subjectArray);
                                //echo "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;New Subject => ".$new_subject_id;
                                // Insert Subject data End
                                $tree = $curriculum->getCategoryTreeDataForImport($sub['SUBJECT_ID']);
                                if (count($tree) && $new_subject_id) {
                                    // print_r($tree);
                                    foreach ($tree as $val) {
                                        $arraytree = array();
                                        $arraytree['SUBJECT_ID'] = $new_subject_id;
                                        $arraytree['CAT_NAME'] = $val['CAT_NAME'];
                                        $arraytree['LFT'] = $val['LFT'];
                                        $arraytree['ADM_REF_ID'] = $val['CAT_ID'];
                                        $arraytree['RGT'] = $val['RGT'];
                                        $arraytree['CAT_FLAG'] = $val['CAT_FLAG'];
                                        $arraytree['STATUS_FLAG'] = $val['STATUS_FLAG'];
                                        $new_syllabus_id = $this->db->savePullCurriculumOutline($arraytree);
                                        $lo = $curriculum->getloForImport($val['CAT_ID']);
                                       //print_r($lo);sizeof($lo);
                                          
                                        if(!empty($lo) && count($lo) && $new_syllabus_id){
                                            foreach($lo as $los){
                                                $loarray=array();
                                               $loarray['ADM_REF_ID'] = $los['LO_ID'];
                                               $loarray['LO_NAME'] = $los['LO_NAME'];
                                               $loarray['TOPIC_ID'] = $new_syllabus_id;
                                               $loarray['ORDER_NO'] = $los['ORDER_NO'];
                                               $loarray['STATUS'] = $los['STATUS'];
                                               $new_lo_id = $this->db->savePullLos($loarray);
                                            }
                                        }
                                    }
                                }
                            }
                        }
            
                    }
                }


                //$this->db->unlockTable();
                $result = ['result' => true, 'message' => 'Data has been imported successfully', 'current_path_redirect' => 'Y'];
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    function contentVerbAction() {
        $content_id = $this->params('id');
        $translator = $this->getServiceLocator()->get('translator');
        $this->initModelObject();
        if ($content_id) {
            $getContentDetail = $this->db->getContentByContentId($content_id);
            // $quizId = $this->db->getQuizIdByContentId($content_id);
            // $sumQusetion = $this->db->sumQusetion($quizId);
            $sumQusetion = '';

            $options = '<div class="col-lg-4">';
            $options .= '<select name="cont_verb[]" class="form-control-static form-control contentverb"  data-width="100%">';
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '1') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // LINK
            if ($getContentDetail['CONTTYPE_ID'] == '2') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // EMBED
            if ($getContentDetail['CONTTYPE_ID'] == '3') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // IMAGE
            if ($getContentDetail['CONTTYPE_ID'] == '4') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // VIDEO
            if ($getContentDetail['CONTTYPE_ID'] == '5') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // AUDIO
            if ($getContentDetail['CONTTYPE_ID'] == '6') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // WIDGET
            if ($getContentDetail['CONTTYPE_ID'] == '7') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // DOCUMENT
            if ($getContentDetail['CONTTYPE_ID'] == '8') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
                $options .= '<option value="Completed">' . $translator->translate("Mark as done") . '</option>';
            }
            // QUIZ
            if ($getContentDetail['CONTTYPE_ID'] == '9') {
                $options .= '<option value="Scored">' . $translator->translate("Score at least") . '</option>';
            }
            //SCORM
            if ($getContentDetail['CONTTYPE_ID'] == '10') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '11') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '12') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '13') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '14') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '15') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            // TEXT
            if ($getContentDetail['CONTTYPE_ID'] == '16') {
                $options .= '<option value="Viewed">' . $translator->translate("View the item") . '</option>';
            }
            $options .= '</select></div>';
            $style = "";
            if ($getContentDetail['CONTTYPE_ID'] != '9') {
                $style = 'style="visibility:hidden;"';
            }
            $options .= '</select></div>';
            $style = "";
            if ($getContentDetail['CONTTYPE_ID'] != '9') {
                $style = 'style="visibility:hidden;"';
            }
            $options .= '<div class="col-lg-3" ' . $style . '><input type="text" class="form-control-static form-control scoreatleast" onkeypress="return isNumberKey(event);" name="score[]" ><input type="hidden" value="' . $sumQusetion . '" class="maxScore"> Out Of ' . $sumQusetion . '</div> ';
            echo $options;
            die;
        }
    }

    function isPublishAction() {
        $array = array();
        $cont_id = $this->params('id');
        $is_publish = (!empty($_POST['IS_PUBLISH'])) ? $_POST['IS_PUBLISH'] : 'N';
        $grade = new GradeTable($this->getAdapter());
        echo $grade->publishUnpublishContent($cont_id, $is_publish);
        die;
    }

    function lpUpdatePublishAction() {
        $array = array();
        $LESSONPLAN_ID = $this->params('id');
        $grade = new GradeTable($this->getAdapter());
        $is_publish = (!empty($_POST['IS_PUBLISH'])) ? $_POST['IS_PUBLISH'] : 'N';

        echo $grade->publishUnpublishContentByLP($LESSONPLAN_ID, $is_publish);
        die;
    }

    private function quizDetail($contentId) {
        $quizDetail = [];
        $CreateQuizTable = $this->initTable('Secure\Model\Quiz\CreateQuizTable');
        $orgId = $this->container->authDetail['ORG_ID'];
        $quizDetail = $CreateQuizTable->getTitleByContId($contentId, false, $orgId)->current();
        $qusList = [];
        if (!empty($quizDetail)) {
            $quizDetail->APPEARANCE = ($quizDetail->APPEARANCE == 'SOQ') ? 'Show one questions at a time' : 'Show all Questions at a time';
            $qusList = $CreateQuizTable->questionList($quizDetail->QUIZ_ID);
            $noOfQus = $CreateQuizTable->sumQusetion($quizDetail->QUIZ_ID);
            $totalQus = $CreateQuizTable->countQuestion($quizDetail->QUIZ_ID);
            $studentAttempt = $CreateQuizTable->getQuizAttempt($quizDetail->QUIZ_ID, $this->container->authDetail['USER_OID']);
            $quizDetail->studentAttempt = $studentAttempt;
            $quizDetail->totalNoOfQus = $noOfQus;
            $quizDetail->totalQuestion = $totalQus;
            return [$quizDetail, $qusList];
        }
        return $quizDetail;
    }

    //CS
    function getECDataFromCSAction() {
        //$this->CommonClass()->setCustomLayout($this,'homeLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $config = $this->serviceLocator->get('config');
        $cloudSearchUrl = $config['cloud_search_endpoint'];
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $requestData = $request->getPost()->toArray();
        }
        //echo '<pre>';print_r($requestData);die;
        $multiplefacetsAll = '';
        $multiplefacetsAll = "&facet.content_type={}&facet.rating={}&facet.country={}&facet.grade={}";
        $multiplefacetsAll2 = "&fq=(and (or mode:'EC'))&facet.content_type={}&facet.rating={}&facet.country={}&facet.grade={}";
        $returnField = "&return=_all_fields,_score&sort=_score desc&size=20";
        $inputString = !empty($requestData['q']) ? $requestData['q'] : '';
        $q = "q=" . urlencode($inputString);
        //$facetDataArr = $this->getMultiplefacetsEC($requestData);
        //if load using scroll via AJAX
        if (!empty($requestData['start'])) {
            $start = $requestData['start'];
            $start = $start * 20;
            $returnField .= "&start=" . $start;
        }
        //$cloudSearchUrlData = $cloudSearchUrl.'?'.$facetDataArr['multiplefacets'].$multiplefacetsAll.$returnField;
        $cloudSearchUrlData = $cloudSearchUrl . '?' . $q . $multiplefacetsAll2 . $returnField;
        //$cloudSearchUrlDataEC = $cloudSearchUrl.'?'.$preCondition.$returnField;
        //echo $cloudSearchUrlData;die;
        if ($cloudSearchUrlData != "") {
            $cloudSearchUrlData = str_replace("'", '%27', $cloudSearchUrlData);
            $cloudSearchUrlData = str_replace(" ", '%20', $cloudSearchUrlData);
            $searchData = json_decode(file_get_contents($cloudSearchUrlData), true);
        }
        //echo '<pre>';print_r($searchData);die;
        $searchDataStr = '';
        if (!empty($searchData['hits']['hit'])) {
            foreach ($searchData['hits']['hit'] as $csData) {
                $ecid = $csData['id'];
                $searchDataStr .= '<div id="ec-' . $ecid . '" class="items col-md-12">
					<p class="media-heading"><a href="#">' . $csData['fields']['title'] . '</a></p>
				</div>';
            }
        }
        echo $searchDataStr;
        die;
    }

    function addTebianLessonplanAction() {
        $lpid = $_POST['lpid'];
        $lpDetail = array();
        $lpDetail = (!empty($lpDetail[0])) ? $lpDetail[0] : array();
        if (count($lpDetail)) {
            $this->initModelObject();
            $subjetc_id = $_POST['local_subject_id'];

            /** Used to get last position of created LP for Position reference of imported LP to get latest position of imported LP. */
            $getLpMasterData = $this->db->fetchData('t_cm_lessonplan_master', ['SUBJECT_ID' => $subjetc_id], ['LP_POSITION'], 'LP_POSITION DESC');
            $getImportedLpPos = (!empty($getLpMasterData)) ? $getLpMasterData[0]['LP_POSITION'] + 1 : 0;

            $lpData = array();
            $lpData['LP_NAME'] = $lpDetail['LP_NAME'];
           // $lpData['TEBIAN_REF_ID'] = $lpDetail['LESSONPLAN_ID'];
            $lpData['LP_POSITION'] = $getImportedLpPos;
            //$subjetc_id = $this->db->getSubIdByCcoRefId($lpDetail['SUBJECT_ID'], $this->container->authDetail['ORG_ID']);

            if (!$subjetc_id) {
                die("Invalid Data");
            }
            $lpData['SUBJECT_ID'] = $subjetc_id;
            $lpData['LEARNING_OBJECTIVE'] = "";
            $lpData['CREATED_BY'] = $this->container->authDetail['USER_OID'];
            $lpData['CREATED_ON'] = date('Y-m-d H:i:s');

            $lp_id = $this->db->addLpData($lpData);
            //echo "LP -> ".$lp_id; echo "<br/>";


            if (count($lpDetail['CONTENT_DATA']) && $lp_id) {
                foreach ($lpDetail['CONTENT_DATA'] as $val) {
                    $newArr = array();
                    $newArr['LESSONPLAN_ID'] = $lp_id;
                    //$newArr['TEBIAN_REF_ID'] = $val['CONT_ID'];
                    $newArr['CONT_TITLE'] = $val['CONT_TITLE'];
                    $newArr['CONT_DESC'] = $val['CONT_DESC'];
                    $newArr['BACKING_FILE'] = $val['BACKING_FILE'];
                    $newArr['FILE_UID'] = $val['FILE_UID'];
                    $newArr['CONT_SRC'] = $val['TEXT_SRC'];
                    $newArr['CONTTYPE_ID'] = $val['CONTTYPE_ID'];
                    $newArr['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                    $content_id = $this->db->addLPContent($newArr);
                    //echo "Cont -> ".$content_id; echo "<br/>";

                    if ($content_id) {
                        $this->saveTebanCatLosAndImage($newArr, $content_id);
                    }
                }
            }
        }
        die;
    }

    //add EC data  [add Learning object library]
    function addEnrichmentContentAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $config = $this->serviceLocator->get('config');
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $translator = $this->getServiceLocator()->get('translator');
            $requestData = $request->getPost()->toArray();
            //echo '<pre>';print_r($requestData);die;
            $this->initModelObject();

            $msg = '';
            if (!empty($requestData['LESSONPLAN_ID'])) {

                $isAdded = $this->db->checkContentAdded($requestData);

                if (!$isAdded) {
                    $requestData['CONT_ORDER'] = $this->db->getContentCountByLpId($requestData['LESSONPLAN_ID']);
                    $requestData['CREATED_BY'] = $this->container->authDetail['USER_OID'];
                    $content_id = $this->db->addLPContent($requestData);

                    if ($content_id) {
                        $this->saveTebanCatLosAndImage($requestData, $content_id);
                        //$result = ['result' => true, 'message' => 'Saved', 'current_path_redirect' => 'Y'];
                        $msg = $translator->translate("Content have been imported successfully");
                        $result = ['result' => true, 'succes' => true, 'message' => $msg, 'target' => '#dispErrMsgPull', 'popupclose' => true];
                    } else {
                        $msg = $translator->translate("Oops! Db error");
                        $result = ['result' => false, 'message' => $msg,];
                    }
                } else {
                    $msg = $translator->translate("Content already added");
                    $result = ['result' => false, 'message' => $msg, 'target' => '#dispErrMsgPull'];
                }
            } else {
                $msg = $translator->translate("Please select lesson plan");
                $result = ['result' => false, 'message' => $msg, 'target' => '#dispErrMsgPull'];
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    function saveTebanCatLosAndImage($requestData, $content_id) {

        $contDetail = array();
        $contDetail = (!empty($contDetail[0])) ? $contDetail[0] : array();

        // Save All Related Images

        if ($requestData['CONTTYPE_ID'] == 4) {



            if (count($contDetail) && !empty($contDetail['CONT_IMAGES']['IMG_BACKING_FILE'])) {
                foreach ($contDetail['CONT_IMAGES']['IMG_BACKING_FILE'] as $key => $img) {
                    $newArr = array();
                    $newArr['IMG_BACKING_FILE'] = $img;
                    $newArr['IMG_DESC'] = $contDetail['CONT_IMAGES']['IMG_DESC'][$key];
                    $newArr['CONT_ID'] = $content_id;
                    $this->db->saveMultipleImages($newArr);
                }
            }
        }

        // Save Exprted Los
        if (!empty($contDetail['LOS']) && count($contDetail['LOS'])) {
            foreach ($contDetail['LOS'] as $val) {
                $cat_id = $this->db->getCatIdByCcoRefId($val['TOPIC_ID'], $this->container->authDetail['ORG_ID']);

                if ($cat_id) {
                    $lo_id = $this->db->getLoIdByCcoRefId($val['ST_LO_ID'], $cat_id);
                    if ($lo_id) {
                        $newArr = array();
                        $newArr['TOPIC_ID'] = $cat_id;
                        $newArr['CONT_ID'] = $content_id;
                        $newArr['ADM_REF_ID'] = $val['ST_LO_ID'];
                        $newArr['ST_LO_ID'] = $lo_id;
                        $this->db->saveContLoCat($newArr);
                    }
                }
            }
        }


        // Save All Related Images

        if ($requestData['CONTTYPE_ID'] == 4) {
            if (count($contDetail) && !empty($contDetail['CONT_IMAGES']['IMG_BACKING_FILE'])) {
                foreach ($contDetail['CONT_IMAGES']['IMG_BACKING_FILE'] as $key => $img) {
                    $newArr = array();
                    $newArr['IMG_BACKING_FILE'] = $img;
                    $newArr['IMG_DESC'] = $contDetail['CONT_IMAGES']['IMG_DESC'][$key];
                    $newArr['CONT_ID'] = $content_id;
                    $this->db->saveMultipleImages($newArr);
                }
            }
        }
    }

    //add EC data  [add Learning object library]
    function addECDataAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $config = $this->serviceLocator->get('config');
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {

            $translator = $this->getServiceLocator()->get('translator');
            $requestData = $request->getPost()->toArray();
            //echo '<pre>';print_r($requestData);die;
            $this->initModelObject();
            //$this->db->getEnrichContentTypeId($requestData['ECID']);
            $finalDataPost['CONT_TITLE'] = $requestData['title'];
            $finalDataPost['CONTTYPE_ID'] = 12;
            $finalDataPost['LESSONPLAN_ID'] = $requestData['LPID'];
            $finalDataPost['CONT_ORDER'] = $this->db->getContentCountByLpId($requestData['LPID']);
            $finalDataPost['EXTERNAL_ID'] = $requestData['ECID'];
            $finalDataPost['CREATED_BY'] = $this->container->authDetail['USER_OID'];
            $exDataExist = $this->db->checkEnrichContent($requestData['ECID'], $requestData['LPID']);
            //echo '<pre>';print_r($exDataExist);die;
            $msg = '';
            if (empty($exDataExist)) {
                $result = $this->db->addLPContent($finalDataPost);
                if ($result)
                    $msg = $translator->translate("Data has been saved successfully");
                $error = false;
            }else {
                $msg = $translator->translate("Data already has been saved");
                $error = true;
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $msgArr = ['msg' => $msg, 'error' => $error, 'cont' => $result];
            echo json_encode($msgArr);
            die;
        }
    }

    // Add Place holder
    function editlolAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $translator = $this->getServiceLocator()->get('translator');
            $postData = $request->getPost()->toArray();
            $lessonplan_id = (!empty($postData['lessonplan_id'])) ? $postData['lessonplan_id'] : null;
            $CONT_ID = (!empty($postData['CONT_ID'])) ? trim($postData['CONT_ID']) : null;
            $title = (!empty($postData['title'])) ? trim($postData['title']) : null;
            $err = "";
            if (empty($title) || $title == '') {
                $err = $translator->translate("Please enter a title");
            }
            if ($err == "") {
                $this->initModelObject();
                if (!empty($CONT_ID))
                    $result = $this->db->updateLolTitleContent($CONT_ID, $title);
                if ($result) {
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $CONT_ID;
                    $result = ['result' => true, 'message' => '1', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'db:error', 'target' => '#dispErrMsgPull'];
                }
            } else {
                $result = ['result' => false, 'message' => $err, 'target' => '#dispErrMsgPull'];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    // Add Place holder
    function addPlaceholderAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $translator = $this->getServiceLocator()->get('translator');
            $postData = $request->getPost()->toArray();
            //print_r($postData);die;
            $lessonplan_id = (!empty($postData['lessonplan_id'])) ? $postData['lessonplan_id'] : null;
            $CONT_ID = (!empty($postData['CONT_ID'])) ? trim($postData['CONT_ID']) : null;
            $placeholder = (!empty($postData['placeholder'])) ? trim($postData['placeholder']) : null;
            $err = "";
            if (empty($placeholder) || $placeholder == '') {
                $err = $translator->translate("Please enter a place holder");
            }
            if ($err == "") {
                $this->initModelObject();
                if (!empty($lessonplan_id)) {
                    $result = $this->db->addPlaceholderContent($lessonplan_id, $placeholder);
                    $CONT_ID = $result;
                }
                if (!empty($CONT_ID)) {
                    $result = $this->db->updatePlaceholderContent($CONT_ID, $placeholder);
                    $lessonplan_id = $this->db->getLessonplanIdByContentId($CONT_ID);
                }
                if ($result) {


                    $LpArray = $this->db->getLessonPlanById($lessonplan_id);

                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $CONT_ID;
                    // $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $CONT_ID;
                    $result = ['result' => true, 'message' => '1', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'db:error', 'target' => '#dispErrMsgPull'];
                }
            } else {
                $result = ['result' => false, 'message' => $err, 'target' => '#dispErrMsgPull'];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    // Add purchased book
    function addAtbAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $lessonplan_id = $postData['lessonplan_id'];
            $book_id = (!empty($postData['BOOK_ID'])) ? $postData['BOOK_ID'] : null;
            $err = "";
            if (empty($book_id)) {
                $err = "Please select a book";
            }
            if ($err == "") {
                $this->initModelObject();
                $result = $this->db->addAtbBookToContent($lessonplan_id, $book_id);
                if ($result) {
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $result;
                    //$redPath = $this->getRequest()->getBasePath().'/grade/lesson-plan/';
                    $result = ['result' => true, 'message' => '1', 'redirectUrl' => $redPath];
                } else {
                    $result = ['result' => false, 'message' => 'db:error', 'target' => '#dispErrMsgPull'];
                }
            } else {
                $result = ['result' => false, 'message' => $err, 'target' => '#dispErrMsgPull'];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //[niu]
    function getMultiplefacetsEC($requestData) {
        $ct_facet = !empty($requestData['ct']) ? $requestData['ct'] : '';
        $country_facet = !empty($requestData['c']) ? $requestData['c'] : '';
        $grade_facet = !empty($requestData['g']) ? $requestData['g'] : '';
        $rating_facet = !empty($requestData['r']) ? $requestData['r'] : '';
        $content_type_arr = $rating_arr = $country_arr = $grade_arr = $subject_arr = [];
        $multiplefacets = $q = "q=" . urlencode($requestData['q']);
        //default condition for EC
        $modeValue = 'EC';
        $multiplefacets .= "&fq=(and ";
        $modeFacet = "(or ";
        $modeFacet .= 'mode:\'' . urlencode($modeValue) . '\'';
        $multiplefacets .= rtrim($modeFacet) . ") ";
        //Content Type .......
        if ($ct_facet != "") {
            //if(empty($author_arr))
            //$multiplefacets .= "&fq=(and ";
            $content_type_arr = explode(",", $ct_facet);
            $ctfacets = "(or ";
            if (!empty($content_type_arr)) {
                foreach ($content_type_arr as $km => $vm) {
                    $ctfacets .= 'content_type:\'' . urlencode($vm) . '\' ';
                }
            }
            $multiplefacets .= rtrim($ctfacets) . ") ";
        }
        //Country Facet .......
        if ($country_facet != "") {
            //if(empty($author_arr) && empty($content_type_arr) && empty($publish_year_arr))
            //$multiplefacets .= "&fq=(and ";
            $country_arr = explode(",", $country_facet);
            $ctfacets = "(or ";
            if (!empty($country_arr)) {
                foreach ($country_arr as $km => $vm) {
                    $ctfacets .= 'country:\'' . urlencode($vm) . '\' ';
                }
            }
            $multiplefacets .= rtrim($ctfacets) . ") ";
        }
        //Grade Facet .......
        if ($grade_facet != "") {
            //if(empty($author_arr) && empty($content_type_arr) && empty($publish_year_arr))
            //$multiplefacets .= "&fq=(and ";
            $grade_arr = explode(",", $grade_facet);
            $ctfacets = "(or ";
            if (!empty($grade_arr)) {
                foreach ($grade_arr as $km => $vm) {
                    $ctfacets .= 'grade:\'' . urlencode($vm) . '\' ';
                }
            }
            $multiplefacets .= rtrim($ctfacets) . ") ";
        }
        //Rating Facet .......  //rating:[2,3]
        if ($rating_facet != "") {
            //if(empty($author_arr) && empty($content_type_arr) && empty($publish_year_arr) && empty($publisher_arr))
            //$multiplefacets .= "&fq=(and ";
            $rating_arr = explode(",", $rating_facet);
            $ctfacets = "(or rating:[" . $rating_facet . "]";
            /*
              if(!empty($rating_arr)){
              foreach($rating_arr as $km=>$vm){
              $ctfacets.='rating:\''.urlencode($vm).'\' ';
              }
              } */
            $multiplefacets .= rtrim($ctfacets) . ") ";
        }
        $multiplefacets .= ')';
        $ret = ['multiplefacets' => $multiplefacets,
            'content_type_arr' => $content_type_arr,
            'country_arr' => $country_arr,
            'grade_arr' => $grade_arr,
            'rating_arr' => $rating_arr
        ];
        return $ret;
    }

    function updateContentOrderAction() {
        $cont_ids = substr($_POST['cont_ids'], 0, -1);
        $pos = $_POST['pos'];
        $this->initModelObject();
        if ($cont_ids) {
            $result = $this->db->updateContentOrder($cont_ids, $pos);
        }
        die('1');
    }

    function scormTestAction() {
        // Add purchased book
        $this->CommonClass()->setCustomLayout($this, 'backendLayout');
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        //require_once("library/Scorm/samples/config.php"); die;
        //require_once('library/Scorm/ScormEngineService.php');
        $CFG->scormcloudorigin = ScormEngineUtilities::getCanonicalOriginString('Piron', 'Test', 'Version 2.0');
        global $CFG;
        $ServiceUrl = $CFG->scormcloudurl;
        $AppId = $CFG->scormcloudappid;
        $SecretKey = $CFG->scormcloudsecretkey;
        $Origin = $CFG->scormcloudorigin;
        $ScormService = new ScormEngineService($ServiceUrl, $AppId, $SecretKey, $Origin);
        $courseService = $ScormService->getCourseService();
        //$importurl = $CFG->wwwroot."/ImportFinish.php";
        $courseListUrl = $CFG->wwwroot . "/CourseListSample.php";
        //$cloudUploadLink = $uploadService->GetUploadUrl($importurl)
        $courseId = uniqid();
        $cloudUploadLink = $courseService->GetImportCourseUrl($courseId, $courseListUrl);
        return $viewModel;
    }

    function uploadTempAction() {
        $chunkData = $_REQUEST;
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getFiles()->toArray();
        //print_r($postData); die;
        $file = $postData['file']['name'];

        $movefile = move_uploaded_file($postData['file']['tmp_name'], "public/upload/" . $file);
        if ($movefile) {
            //chmod(getcwd() ."/public/upload/" . $file, 777);

            $filedetails['filename'] = $file;
        } else {
            $filedetails['filename'] = "";
        }
        echo json_encode($filedetails);
        die;
    }

    // Add Place holder
    function addScormAction() {
        $contentId = $this->params('id');
        $translator = $this->getServiceLocator()->get('translator');
        $err = '';
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();

//        $catStr = (!empty($postData['TOPIC_ID'])) ? $postData['TOPIC_ID'] : '';
//        $catArr = (!empty($catStr)) ? explode(',', $catStr) : [];
        $catArr = !empty($postData['topic']) ? $postData['topic'] : array();
        $result = [];
        $array['LESSONPLAN_ID'] = (!empty($postData['LESSONPLAN_ID'])) ? $postData['LESSONPLAN_ID'] : null;
        $this->initModelObject();
        if (!empty($postData['topic'])) {
            if (empty($contentId)) {
                $array['CONT_TITLE'] = (!empty($postData['CONT_TITLE'])) ? trim($postData['CONT_TITLE']) : ' ';
                $array['SCORM_COURSE_ID'] = (!empty($postData['SCORM_COURSE_ID'])) ? trim($postData['SCORM_COURSE_ID']) : null;
                $array['CREATED_ON'] = date('Y-m-d H:i:s');
                if ($err == "") {
                    $CONT_ID = $this->db->saveScorm($array);

                    $this->db->deleteData('t_cm_cont_cat', ['CONT_ID' => $CONT_ID]);
                    for ($i = 0; $i < count($catArr); $i++) {
                        $InsData = [];
                        $InsData = ['CONT_ID' => $CONT_ID, 'CAT_ID' => $catArr[$i]];
                        $this->db->insertData('t_cm_cont_cat', $InsData);
                    }
                    $lessonplan_id = $postData['LESSONPLAN_ID'];
                    $LpArray = $this->db->getLessonPlanById($lessonplan_id);
                    $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $CONT_ID;
                    // $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $CONT_ID;
                    $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'innerhtml' => true, 'redirectUrl' => $redPath];
                }
            } else {
                $this->db->deleteData('t_cm_cont_cat', ['CONT_ID' => $contentId]);
                for ($i = 0; $i < count($catArr); $i++) {
                    $InsData = [];
                    $InsData = ['CONT_ID' => $contentId, 'CAT_ID' => $catArr[$i]];
                    $this->db->insertData('t_cm_cont_cat', $InsData);
                    $lessonplan_id = $this->db->getLessonplanIdByContentId($contentId);
                    $LpArray = $this->db->getLessonPlanById($lessonplan_id);
                }


                $redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan/' . $LpArray['SUBJECT_ID'] . '?cont=content' . $contentId;
                //$redPath = $this->getRequest()->getBasePath() . '/grade/lesson-plan?cont=content' . $contentId;
                $result = ['result' => true, 'message' => $translator->translate('Data has been saved successfully'), 'innerhtml' => true, 'redirectUrl' => $redPath];
            }
        } else {
            if (empty($postData['topic'])) {
                $result = ['result' => false, "target" => "#errordiv", 'innerhtml' => true, 'message' => $translator->translate("Please choose at least one topic")];
            }
//            if (empty($postData['learning_objective'])) {
//                die("sadsa");
//                $result = ['result' => false, "target" => "#errordivforlo",  'message' => $translator->translate("Please add learning objective")];
//            }
//            $formMsgArr['TOPIC_ID']['isEmpty'] = $translator->translate("Value is required and can't be empty");
//            $result = ['result' => false, 'message' => $formMsgArr];
        }
        $viewModel = new JsonModel();
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    function scormAction() {
        $baseDirPath = getcwd() . '/library/';
        require_once($baseDirPath . "scorm/ScormEngineUtilities.php");
        require_once($baseDirPath . 'scorm/ScormEngineService.php');
        $uploadFolderPath = "";
        if (!empty($_POST['filename'])) {
            $uploadFolderPath = getcwd() . '/public/upload/' . $_POST['filename'];
        } else {
            $array['title'] = $_POST['filename'];
            $array['upload'] = 0;
            echo json_encode($array);
            die;
        }
        $config = $this->serviceLocator->get('config');
        $ServiceUrl = $config['scorm_serviceurl'];
        $SecretKey = $config['scorm_secretkey'];
        $AppId = $config['scorm_appid'];
        $Origin = ScormEngineUtilities::getCanonicalOriginString('Piron', 'Test', 'Version 2.0');
        $ScormService = new ScormEngineService($ServiceUrl, $AppId, $SecretKey, $Origin);

        $courseService = $ScormService->getCourseService();
        $courseId = uniqid();

        $response = $courseService->ImportCourse($courseId, $uploadFolderPath);

        $response = $this->toArray2($response[0]);
        //print_r($response); die;
        $test = [];
        foreach ($response as $key => $resp) {
            $test[] = "$key=>$resp";
        }
        /*         * ************************************
          DATA FORMAT LOOKS LIKE BELLOW:
          [0] => ImportResult_title=>Golf Explained - Run-time Advanced Calls
          [1] => ImportResult_wasSuccessful=>1
          [2] => ImportResult_message=>Import Successful
          [3] => ImportResult_parserWarnings=>Array
         * ************************************ */
        $array = array();
        $result = end(explode("=>", $test[2]));
        $title = end(explode("=>", $test[0]));
        if ($result == 'Import Successful') {
            $array['title'] = $title;
            $array['courseId'] = $courseId;
            $array['upload'] = 'ok';
            unlink($uploadFolderPath);
        } else {
            $array['title'] = $title;
            $array['upload'] = 0;
        }
        echo json_encode($array);
        die;
    }

    function deleteScorm($courseid) {
        $baseDirPath = getcwd() . '/library/';
        require_once($baseDirPath . "scorm/ScormEngineUtilities.php");
        require_once($baseDirPath . 'scorm/ScormEngineService.php');
        $config = $this->serviceLocator->get('config');
        $ServiceUrl = $config['scorm_serviceurl'];
        $SecretKey = $config['scorm_secretkey'];
        $AppId = $config['scorm_appid'];
        $Origin = ScormEngineUtilities::getCanonicalOriginString('Piron', 'Test', 'Version 2.0');
        $ScormService = new ScormEngineService($ServiceUrl, $AppId, $SecretKey, $Origin);
        $courseService = $ScormService->getCourseService();
        $courseService->DeleteCourse($courseid, 'false');
        return true;
    }

    function toArray2($obj) {
        if (is_object($obj))
            $obj = (array) $obj;
        if (is_array($obj)) {
            $new = array();
            foreach ($obj as $key => $val) {
                $new[$key] = $this->toArray2($val);
            }
        } else {
            $new = $obj;
        }
        return $new;
    }

    /**
     * @desc Get desired lesson-plan(s) with their check-box HTML by LPID.
     */
    public function getLpByLpselectionAction() {
        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $translator = $this->getServiceLocator()->get('translator');
        $request = $this->getRequest();
        $option = '';
        if ($request->isXmlHttpRequest()) {
            $this->db = new GradeTable($dbadapter);
            $postData = $request->getPost()->toArray();

            $condArr['subject_id'] = $postData['subject_id'];
            $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
            $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];
            $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
            /** Get lesson-plan position via its id */
            $lpPosDetail = $this->db->fetchData('t_cm_lessonplan_master', ['LESSONPLAN_ID' => $postData['lessonplan_id']], ['LP_POSITION'], null, false);

            $condArr['LP_ST_POSITION'] = $lpPosDetail['LP_POSITION'];
            $userIds = $this->db->getuserIdsByOrgId($condArr['ORG_ID']);
            $lpData = !empty($condArr['LP_ST_POSITION']) ? $this->db->getLessonPlanData($condArr, $userIds) : [];

            if (count($lpData)) {
                $option = '<label class="pb-10 pr-10 pt-10"><strong>' . $translator->translate('Included Lesson Plan') . ': </strong></label>';
                foreach ($lpData as $data) {
                    $option .= '<div class="checkbox">
                                    <label><input type="checkbox" name="LP_ID[]" value="' . $data['LESSONPLAN_ID'] . '" class="styled">' . $data['LP_NAME'] . '</label>
                                </div>';
                }
            }
            echo $option;
            die;
        }
    }

    /**
     * @desc used to save SUMMATIVE-TEST form`s data
     * @return type
     */
    function saveSummativeTestAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $translator = $this->getServiceLocator()->get('translator');
        $questionPreviewHelper = $this->getHelperManager()->get('QuestionPreviewHelper');
        $isApi = $questionPreviewHelper->isTestEnable();

        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        $quizId = !empty($this->params('id')) ? $this->params('id') : 0;
        $result = ['result' => false, 'message' => ""];
        $errorInForm = [];
        if ($request->isPost() && $request->isXmlHttpRequest()) {
            $this->initModelObject();
            $viewModel->setTerminal(true);

            $userId = $this->container->authDetail['USER_OID'];
            $condArr['subject_id'] = $postData['SUBJECT_ID'];
            $condArr['UT_ID'] = $this->container->authDetail['UT_ID'];
            $condArr['ORG_ID'] = $this->container->authDetail['ORG_ID'];
            $condArr['USER_OID'] = $this->container->authDetail['USER_OID'];
            $userIds = $this->db->getuserIdsByOrgId($condArr['ORG_ID']);
            $lpData = $this->db->getLessonPlanData($condArr, $userIds);

            $summativeForm = new \Secure\Form\Grade\AddSummativeTestForm($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'), $this->container->authDetail, $lpData);
            $summativeFilter = new \Secure\Model\Grade\AddSummativeTestInputFilter($this->getServiceLocator()->get('Zend\Db\Adapter\Adapter'));
            $summativeForm->setInputFilter($summativeFilter->getInputFilter());
            $summativeForm->setData($request->getPost());

            $data['ST_POSITION'] = !empty($postData['ST_POSITION']) ? $postData['ST_POSITION'] : 0;
            $testDetail = $this->db->fetchData('t_master_test', ['ST_POSITION' => $data['ST_POSITION'], 'QUIZ_TYPE' => 'ST', 'CREATED_BY' => $userIds, 'SUBJECT_ID' => $postData['SUBJECT_ID']], ['ST_POSITION', 'QUIZ_ID'], null, false);
            $testLpCount = $this->db->countData('t_mgr_test_lessonplan', ['QUIZ_ID' => $quizId]);
            $lpCount = $this->db->countData('t_cm_lessonplan_master', ['SUBJECT_ID' => $postData['SUBJECT_ID']]);

            if ($testDetail['ST_POSITION'] && $testDetail['QUIZ_ID'] != $quizId) {
                $errorInForm['ST_POSITION'] = ['isPosExist' => $translator->translate('Already assigned position for test.')];
            } else if ((empty($postData['ST_POSITION']))) {
                $errorInForm['ST_POSITION'] = ['isSelectPos' => $translator->translate('Please select a position.')];
            } else if (!isset($postData['LP_ID']) && !$testLpCount) {
                $errorInForm['ST_POSITION'] = ['isSelectLp' => $translator->translate('Please select atleast one lesson plan.')];
            } else if (!$lpCount) {
                $errorInForm['ST_POSITION'] = ['isLpExist' => $translator->translate('A lesson plan required')];
            }
            if ($summativeForm->isValid() && !count($errorInForm)) {
                $dataToLpTest = [];
                if (!empty($quizId)) {
                    $dataToTest = [
                        'TITLE' => $postData['ST_NAME'],
                        'ST_POSITION' => $data['ST_POSITION'],
                        'UPDATED_ON' => date('Y-m-d H:i:s'),
                        'UPDATED_BY' => $userId,
                    ];
                    $isUpdated = $this->db->updateData('t_master_test', $dataToTest, ['QUIZ_ID' => $quizId]);

                    /** Insert Entry into LP-test reference table with existed id`s deletion */
                    if ($quizId) {
                        /** new fresh entry if exist for test's LP in associated table after deletion */
                        if (isset($postData['LP_ID']) && count($postData['LP_ID'])) {
                            /** Deletion before new entry in test's LP table in edit mode only */
                            if ($testLpCount) {
                                $this->db->deleteData('t_mgr_test_lessonplan', ['QUIZ_ID' => $quizId]);
                            }
                            foreach ($postData['LP_ID'] as $lpdataVal) {
                                $dataToLpTest = [
                                    'QUIZ_ID' => $quizId,
                                    'LESSONPLAN_ID' => $lpdataVal,
                                ];
                                $this->db->insertData('t_mgr_test_lessonplan', $dataToLpTest);
                            }
                        } else if ($postData['position'] == 'begin') {
                            /** An entry for beginning case (beginning tab) only when no LP selected by check-boxes */
                            /** Deletion before new entry in test's LP table in edit mode only */
                            if ($testLpCount) {
                                $this->db->deleteData('t_mgr_test_lessonplan', ['QUIZ_ID' => $quizId]);
                            }
                            $dataToLpTest = [
                                'QUIZ_ID' => $quizId,
                                'LESSONPLAN_ID' => $lpData[0]['LESSONPLAN_ID'],
                            ];
                            $this->db->insertData('t_mgr_test_lessonplan', $dataToLpTest);
                        }
                    }
                } else {
                    /** Insert Entry into test table with type ST */
                    $dataToTest = [
                        'TITLE' => $postData['ST_NAME'],
                        'SUBJECT_ID' => $postData['SUBJECT_ID'],
                        'ST_POSITION' => $data['ST_POSITION'],
                        'QUIZ_TYPE' => 'ST',
                        'CREATED_ON' => date('Y-m-d H:i:s'),
                        'CREATED_BY' => $userId,
                    ];
                    $quizId = $this->db->insertData('t_master_test', $dataToTest);

                    /** Insert Entry into LP-test reference table */
                    if ($quizId) {
                        if (isset($postData['LP_ID']) && count($postData['LP_ID'])) {
                            foreach ($postData['LP_ID'] as $lpdataVal) {
                                $dataToLpTest = [
                                    'QUIZ_ID' => $quizId,
                                    'LESSONPLAN_ID' => $lpdataVal,
                                ];
                                $this->db->insertData('t_mgr_test_lessonplan', $dataToLpTest);
                            }
                        } else if ($postData['position'] == 'begin') {
                            /** An entry for beginning case (beginning tab) only when no LP selected by check-boxes */
                            $dataToLpTest = [
                                'QUIZ_ID' => $quizId,
                                'LESSONPLAN_ID' => $lpData[0]['LESSONPLAN_ID'],
                            ];
                            $this->db->insertData('t_mgr_test_lessonplan', $dataToLpTest);
                        }
                    }
                }
                if ($quizId) {
                    /** If Tebian API Enabled school/teacher. */
                    if ($isApi == 'Y') {
                        return $this->redirect()->toRoute(
                                        'test', array(
                                    'action' => 'edit',
                                    'id' => $quizId
                                        ), array(
                                    'query' =>
                                    array(
                                        'module' => 'test',
                                        'router' => 'test',
                                        'test_type' => 'ST',
                                        'TEST_NAME' => $postData['ST_NAME'],
                                        'edit_from' => $postData['edit_from']
                                    )
                                        )
                        );
                    } else {
                        /** If Tebian API Disabled school/teacher. */
                        return $this->redirect()->toRoute(
                                        'assessment', array(
                                    'action' => 'save-test',
                                    'id' => $quizId
                                        ), array(
                                    'query' =>
                                    array(
                                        'module' => 'assessment',
                                        'router' => 'assessment',
                                        'test_type' => 'ST',
                                        'TEST_NAME' => $postData['ST_NAME']
                                    )
                                        )
                        );
                    }
                } else {
                    $result = ['result' => false, 'message' => 'DB:Error'];
                }
            } else {
                $zendFormErrorMsg = $summativeForm->getMessages();
                $errorMsg = array_merge($errorInForm, $zendFormErrorMsg);
                $result = ['result' => false, 'message' => $errorMsg];
            }
        }
        $viewModel->setVariables(['data' => $result]);
        return $viewModel;
    }

    //lesson plan detail page to show all types of file in player
//    function summativeTestDetailAction() {
//
//        $translator = $this->getServiceLocator()->get('translator');
//        $testId = $this->params('id');
//        $this->initModelObject();
//        $ordId = $this->container->authDetail['ORG_ID'];
//        $uId = $this->container->authDetail['USER_OID'];
//        
//        $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
//        $grade = new GradeTable($dbadapter);
//        $displaybook = 0;
//        if ($testId) {
//            $quizDetail = array();
//            $getLessionId = $this->db->getLessonplanIdByContentId($contentId);
//            $condArr['LP_ID'] = $getLessionId;
//            $userIds = $this->db->getuserIdsByOrgId($this->container->authDetail['ORG_ID']);
//            $lpData = $this->db->getLessonPlanData($condArr, $userIds);
//            $contentData = $this->db->getContentByContentId($contentId);
//            
//        } else {
//            return $this->redirect()->toRoute('grade', array('action' => 'lesson-plan'));
//        }
//        $param = [
//            'title' => $contentData['CONT_TITLE'] . " - " . $translator->translate("Kalemon"),
//            'keywords' => $contentData['CONT_TITLE'],
//            'description' => $contentData['CONT_TITLE']
//        ];
//        $this->CommonClass()->setMetaData($this, $param);
//        $this->CommonClass()->setCustomLayout($this, 'lpLayout');
//        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
//        $viewModel->setVariables([
//            'lpData' => $lpData,
//            "contentId" => $contentId,
//            "contentData" => $contentData,
//            'authDetail' => $this->container->authDetail,
//            'quizDetail' => $quizDetail,
//            'displaybook' => $displaybook,
//            'title' => "SK",
//            'keywords' => "SK",
//            'description' => "SK",
//            
//        ]);
//        return $viewModel;
//    }
}

Youez - 2016 - github.com/yon3zu
LinuXploit