<?php
/****************************
 * File : topics.php
 * Author : Cygnusa
 * @2018
 ****************************/

//SECURITY
if (!defined('APPLICATION_PATH')) {
    exit('No direct script access allowed');
}

class topics
{

    //FUNCTION LISTS
    public function __construct($parent)
    {
        //GET PAGE MESSAGE
        $this->page_data = globalfunc::getMessage($parent, $parent->lang, 'topics');
        if (count($parent->params) == 0) {
            //$this->topicsfunc($parent);
        } else {
            $qry_params = explode("?", $parent->params[0]);
            $parameter_val = strtolower($qry_params[0]);

            if (strtolower($parent->device_type) == 'app') {
                switch ($parameter_val) {
                    case "content":
                    case "content_status":
                    case "get_content_details":
                        $this->$parameter_val($parent);
                        break;
                    default:
                        $this->topicsfunc($parent);
                        break;
                }
            } else if (strtolower($parent->device_type) == 'web') {
                switch ($parameter_val) {
                    case "content":
                    case "content_status":
                    case "get_content_details":
                        $this->$parameter_val($parent);
                        break;

                    default:
                        $this->topicsfunc($parent);
                        break;
                }
            }
        }

        $parent->response(array('response' => 'failed', 'message' => 'PAGE NOT FOUND'), 404);
    }

    /* /////////////////////////////// TOPICS LIST //////////////////////////////////////////////// */
    private function topicsfunc($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        //PAGINATION SETTINGS
        $limit_cond = '';
        $data_arr = array();
        $limit_str = globalfunc::setPageLimit($parent, $parent->params[0]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $data = @explode('?', $parent->params[0]);
        $cateid = escape_str($data[0]); //GET CATE ID
        $userid = $parent->current_user_id;
        //USER FILTER CONDITION APPLY
        $user_cond = " AND cateid='" . $cateid . "' ";

        $user_cond .= ($parent->current_user_role == 15) ? " AND assettopicid=61" : "AND assettopicid!=61";

        //NEW ROLE CONDITION
        //$user_cond.=($parent->current_user_role>7 && $parent->current_user_role<14)?" AND user_type=0 ":" AND user_type=1 ";

        //NEW SEGMENT CONDITION
        if ($parent->current_user_role > 7 && $parent->current_user_role < 14) {
            $user_cond .= " AND (segment='0' OR segment='" . $parent->current_user_data->segment . "')";
        }

        ///////////////////////////////////////////////////////////////////////////////////////
        $check_user_str = "SELECT  userid,segment,role FROM " . TABLE_USER . "  WHERE  status='1' AND is_deleted='0' AND userid='" . $userid . "' LIMIT 1";
        $check_user_arr = $parent->getQueryValue($check_user_str);
        if (!count($check_user_arr) > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data["error2"]), 406);
        }

        if ($check_user_arr[0]->role > 7 && $check_user_arr[0]->role < 14) {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role', 'zone', 'city', 'dealer_code'), $userid);
        } else {
            $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role'), $userid);
        }
        $peruser_cond = str_replace("filter_", "c.filter_", $user_filter_str);

        if ($check_user_arr[0]->role > 7 && $check_user_arr[0]->role < 14) {
            switch ($check_user_arr[0]->segment) {
                case "1":$peruser_cond .= " AND t.segment IN (0,1)  AND c.segment IN (0,1)";
                    break;
                case "2":$peruser_cond .= " AND t.segment IN (0,2)  AND c.segment IN (0,2)";
                    break;
                default:$peruser_cond .= " AND t.segment IN (0)  AND c.segment IN (0)";
                    break;
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////

        $getuser_topics_arr = $parent->selectQuery(TABLE_ASSET_TOPIC, "*", " status='1' AND is_deleted='0' " . $user_cond . " ORDER BY position ASC, assettopicid ASC " . $limit_cond, "");
        if ($getuser_topics_arr['nr']) {
            //CONNECT S3
            $s3 = awsfileserver::connectS3();
            foreach ($getuser_topics_arr['result'] as $res) {
                $res->image_url = TRAININGIMAGE_URL;
                if ($res->image) {
                    $res->image_url = awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_TOPICS_URL . $res->image);
                }

                $get_course_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $cateid . "' AND  t.assettopicid='" . $res->assettopicid . "'  " . $peruser_cond;

                $res->total_q = $get_course_str;

                $get_course_arr = $parent->getQueryValue($get_course_str);
                $total_content = (count($get_course_arr) > 0) ? $get_course_arr[0]->totcontent : '0';

                //GET USER COMPLETED CONTENT COUNT
                $get_user_completed_str = "SELECT COUNT(c.`contentid`) as totcontent FROM " . TABLE_ASSET_CONTENT . " as c JOIN " . TABLE_ASSET_TOPIC . " as t ON t.assettopicid=c.assettopicid JOIN (SELECT * FROM " . TABLE_USER_COMPLETE_CONTENT . " WHERE userid='" . $userid . "' AND status='2') as a ON a.contentid=c.contentid WHERE t.status='1' AND t.is_deleted='0' AND c.status='1' AND c.is_deleted='0' AND t.cateid='" . $cateid . "'  AND  t.assettopicid='" . $res->assettopicid . "' " . $peruser_cond;
                $get_user_completed_arr = $parent->getQueryValue($get_user_completed_str);
                $user_content = (count($get_user_completed_arr) > 0) ? $get_user_completed_arr[0]->totcontent : '0';
                //$res->total_cq = $get_user_completed_str;
                $res->total = ($total_content > 0) ? $total_content : '0';
                $res->completed = ($user_content > 0) ? $user_content : '0';
                $res->percentage = ($total_content > 0) ? round(($user_content / $total_content) * 100) : '0';

                $data_arr[] = $res;
            }
        }

        //GET COUNT
        $getuser_topics_count = $parent->selectQuery(TABLE_ASSET_TOPIC, "COUNT(assettopicid)as topic_count", " status='1' AND is_deleted='0' " . $user_cond, "1");
        $total = ($getuser_topics_count['nr']) ? $getuser_topics_count['result'][0]->topic_count : 0;

        //LOG
        $logstr = 'TOPICS';
        globalfunc::insertUserLog($parent, $logstr, $cateid);

        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TOPICS CONTENT LIST //////////////////////////////////////////////// */
    private function content($parent)
    {
        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        //PAGINATION SETTINGS
        $limit_cond = '';
        $data_arr = array();

        $limit_str = globalfunc::setPageLimit($parent, $parent->params[1]);
        $limit_cond = ($limit_str) ? " LIMIT " . $limit_str : '';
        $data = @explode('?', $parent->params[1]);
        $assettopicid = escape_str($data[0]);
        //$lvl_id= projectfunc::getUserLvlId($parent);
        //AND lvl_id='".$lvl_id."'

        //NEW ROLE CONDITION
        //$user_cond.=($parent->current_user_role>7 && $parent->current_user_role<14)?" AND user_type=0 ":" AND user_type=1 ";

        $seg_cond = '';
        //NEW SEGMENT CONDITION
        if ($parent->current_user_role > 7 && $parent->current_user_role < 14) {
            $seg_cond .= " AND (segment='0' OR segment='" . $parent->current_user_data->segment . "')";
        }
        //CHECK TOPIC VALIDATION
        $getcheck_topic = $parent->selectQuery(TABLE_ASSET_TOPIC, "*", " status='1' AND is_deleted='0' " . $user_cond . " AND assettopicid='" . $assettopicid . "' ", "1");
        if (!$getcheck_topic['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error1']), 406);
        }

        //ORDER BY COND
        $orderby_cond = ($getcheck_topic['result'][0]->listorder == '1') ? "ORDER BY uploaddate DESC,contentid ASC " : "ORDER BY uploaddate ASC,contentid ASC ";

        //USER FILTER CONDITION APPLY
        $user_cond = " AND assettopicid='" . $assettopicid . "' " . $seg_cond;

        //COMMAN USER FILTER
        $user_filter_str = projectfunc::getUserfiltervalue($parent, array('role', 'zone', 'city', 'dealer_code'));
        $user_cond .= $user_filter_str;

        $getuser_content_arr = $parent->selectQuery(TABLE_ASSET_CONTENT, "*", " status='1' AND is_deleted='0' " . $user_cond . " " . $orderby_cond . $limit_cond, "");
        if ($getuser_content_arr['nr']) {
            //CONNECT S3
            $s3 = awsfileserver::connectS3();
            foreach ($getuser_content_arr['result'] as $res) {
                //GET USER STATUS OF CONTENT
                $content_status_arr = projectfunc::getContentStatus($parent, $res->contentid);
                $res->status = $content_status_arr['status'];
                $res->status_str = $content_status_arr['status_str'];

                $res->content_files = $this->getContentFiles($parent, $s3, $res->contentid);
                $data_arr[] = $res;
            }
        }

        //GET COUNT
        $getuser_content_count = $parent->selectQuery(TABLE_ASSET_CONTENT, "COUNT(contentid)as content_count", " status='1' AND is_deleted='0' " . $user_cond, "1");
        $total = ($getuser_content_count['nr']) ? $getuser_content_count['result'][0]->content_count : 0;

        //LOG
        $logstr = 'CONTENT';
        globalfunc::insertUserLog($parent, $logstr, $assettopicid);

        $last_page = ($total) ? ceil($total / $parent->current_limit) - 1 : 0;
        $parent->response(array('response' => 'success', 'data' => $data_arr, 'total' => $total, 'last_page' => $last_page, 'current_page' => $parent->current_page, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TOPIC CONTENT  //////////////////////////////////////////////// */
    private function getContentFiles($parent, $s3, $contentid)
    {
        $data_arr = array();
        //GET FILES ONLY ONE FILE
        $getuser_contentfiles_arr = $parent->selectQuery(TABLE_ASSET_FILE . " as f JOIN " . TABLE_MASTER_LANGUAGE . " as l ON l.language_id=f.language_id", " f.`language_id`, f.`filepath`,f.filetypeid, f.`thumbpath`, f.`filetypeid`, f.`filetype`, f.`filesize`, f.`filequality`, l.`language_code`, l. `language_title`", " f.contentid='" . $contentid . "' ORDER BY l.language_title ASC,f.id ASC ", "");
        if ($getuser_contentfiles_arr['nr']) {
            foreach ($getuser_contentfiles_arr['result'] as $tkey => $res) {
                //S3 FILE URL
                $fileurl = '';
                if ($res->filepath != '') {
                    $url = awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_TOPICS_URL . $res->filepath);
                    //PDF ISSUE FIX FOR WEB DEVICE
                    $url = (strtolower($parent->device_type) == 'web' && $res->filetypeid == '1') ? projectfunc::pdfUrlStr($parent, $url) : $url;
                    $fileurl = $url;
                }
                $getuser_contentfiles_arr['result'][$tkey]->file_url = $fileurl;
                //S3 THUMBIMAGE URL
                $thumb_fileurl = '';
                if ($res->thumbpath != '') {
                    $thumb_fileurl = awsfileserver::getS3FileUrl($s3, S3_BUCKET, S3_TOPICS_URL . $res->thumbpath);
                }
                $getuser_contentfiles_arr['result'][$tkey]->thumb_fileurl = $thumb_fileurl;
            }

            $data_arr = $getuser_contentfiles_arr['result'];
        }

        return $data_arr;
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// USER COMPLETE CONTENT TABLE  //////////////////////////////////////////////// */
    private function content_status($parent)
    {
        globalfunc::checkMethodType($parent, array('POST'));
        globalfunc::checkParamCount($parent, 1);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $REQUEST_KEYS = array('status' => 'integer', 'contentid' => 'integer', 'assettopicid' => 'integer');
        globalfunc::mandatoryKey($parent, $REQUEST_KEYS);

        $contentid = escape_str($parent->_request['contentid']);
        $assettopicid = escape_str($parent->_request['assettopicid']);
        $status = escape_str($parent->_request['status']); //0-started, 1-In progress, 2-Completed

        $completeddate = '';
        if ($status == '2') {
            $completeddate = CUR_DATE;
        }

        //GET USER Level ID
        //$lvl_id= projectfunc::getUserLvlId($parent);
        //AND lvl_id='".$lvl_id."'

        //NEW ROLE CONDITION
        //$user_cond.=($parent->current_user_role>7 && $parent->current_user_role<14)?" AND user_type=0 ":" AND user_type=1 ";

        $seg_cond = '';
        //NEW SEGMENT CONDITION
        if ($parent->current_user_role > 7 && $parent->current_user_role < 14) {
            $seg_cond .= " AND (segment='0' OR segment='" . $parent->current_user_data->segment . "')";
        }

        //CHECK TOPIC VALIDATION
        $getcheck_topic = $parent->selectQuery(TABLE_ASSET_TOPIC, "*", " status='1' AND is_deleted='0' AND assettopicid='" . $assettopicid . "' " . $user_cond . " " . $seg_cond, "1");
        if (!$getcheck_topic['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error1']), 406);
        }

        $cateid = $getcheck_topic['result'][0]->cateid;

        //GET CONTENT STATUS
        $query_user_status = $parent->selectQuery(TABLE_USER_COMPLETE_CONTENT, "*", " userid='" . $parent->current_user_id . "' AND assettopicid='" . $assettopicid . "' AND contentid='" . $contentid . "'", "1");

        if ($query_user_status['nr'] > 0) {
            //UPDATE
            if ($query_user_status['result'][0]->status != 2) {
                $econd = ($completeddate != '') ? ", completeddate='" . $completeddate . "'" : '';
                $update_user_status_str = "UPDATE " . TABLE_USER_COMPLETE_CONTENT . " SET status='" . $status . "',modified_on='" . NOW . "' " . $econd . " WHERE id='" . $query_user_status['result'][0]->id . "'";
            }
        } else {
            //INSERT
            $update_user_status_str = "INSERT INTO " . TABLE_USER_COMPLETE_CONTENT . " (`cateid`, `assettopicid`, `contentid`, `userid`, `status`, `completeddate`, `created_on`, `modified_on`) VALUES ('" . $cateid . "', '" . $assettopicid . "','" . $contentid . "','" . $parent->current_user_id . "','" . $status . "','" . $completeddate . "','" . NOW . "','" . NOW . "') ";
        }
        $parent->executeQuery($update_user_status_str);

        //LOG
        $logstr = 'CONTENT STATUS UPDATE';
        globalfunc::insertUserLog($parent, $logstr, $contentid);

        $parent->response(array('response' => 'success', 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TOPICS CONTENT DETAILS //////////////////////////////////////////////// */
    private function get_content_details($parent)
    {

        globalfunc::checkMethodType($parent, array('GET'));
        globalfunc::checkParamCount($parent, 2);
        globalfunc::checkAuthrozation($parent, array('type' => 'user'));

        $data = @explode('?', $parent->params[1]);
        $contentid = escape_str($data[0]);
        $data_arr = array();
        //GET USER Level ID
        // $lvl_id= projectfunc::getUserLvlId($parent);
        // AND lvl_id='".$lvl_id."'

        //NEW ROLE CONDITION
        //$user_cond.=($parent->current_user_role>7 && $parent->current_user_role<14)?" AND user_type=0 ":" AND user_type=1 ";

        $seg_cond = '';
        //NEW SEGMENT CONDITION
        if ($parent->current_user_role > 7 && $parent->current_user_role < 14) {
            $seg_cond .= " AND (segment='0' OR segment='" . $parent->current_user_data->segment . "')";
        }

        //CHECK TOPIC VALIDATION
        $getcheck_topic = $parent->selectQuery(TABLE_ASSET_TOPIC, "*", " status='1' AND is_deleted='0' " . $user_cond . " AND assettopicid IN (SELECT assettopicid FROM " . TABLE_ASSET_CONTENT . " WHERE contentid='" . $contentid . "')" . $seg_cond, "1");
        if (!$getcheck_topic['nr'] > 0) {
            $parent->response(array('response' => 'failed', 'message' => $this->page_data['error1']), 406);
        }

        //USER FILTER CONDITION APPLY
        $user_cond = " AND contentid='" . $contentid . "' ";
        $getuser_content_arr = $parent->selectQuery(TABLE_ASSET_CONTENT, "*", " status='1' AND is_deleted='0' " . $user_cond . $seg_cond, "1");
        if ($getuser_content_arr['nr']) {
            //CONNECT S3
            $s3 = awsfileserver::connectS3();
            foreach ($getuser_content_arr['result'] as $res) {
                //GET USER STATUS OF CONTENT
                $content_status_arr = projectfunc::getContentStatus($parent, $res->contentid);
                $res->status = $content_status_arr['status'];
                $res->status_str = $content_status_arr['status_str'];
                $res->content_files = $this->getContentFiles($parent, $s3, $res->contentid);
                $data_arr = $res;
            }
        }

        //LOG
        $logstr = 'CONTENT DETAILS';
        globalfunc::insertUserLog($parent, $logstr, $contentid);

        $parent->response(array('response' => 'success', 'data' => $data_arr, 'message' => $this->page_data['success1']), 200);
    }
    /* //////////////////////////////////////////////////////////////////////////////////////////// */

}
