<?php
include "Connection.php";
$conn = new Connection();


if(isset($_REQUEST["funName"])) {
	$db = $conn->getConnection();
	$fun = $_REQUEST["funName"];
	switch($fun) {
        case "productlist":
        case "addproduct":
        case "updateproduct":
        case "deleteproduct":
            $fun();
        break;	
        default:
            $conn->message(false,"PAGE NOT FOUND");exit;
        break;		 
	}
}else
{
      $conn->message(false,"PAGE NOT FOUND");exit;
}

// PRODUCTLIST
function productlist () {
        
	global $conn;
	try {
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';		
		$pn = escape_str($_REQUEST["pn"]);
		$nr = escape_str($_REQUEST["nr"]);
		$key = escape_str($_REQUEST["key"]);
        $cateid = escape_str($_REQUEST['cateid']);
        
		if(isset($_SESSION["userid"])) {
			$query_str = "SELECT SQL_CALC_FOUND_ROWS t.*, CASE WHEN t.segment=0 THEN 'Student Learner' WHEN t.segment=1 THEN 'Parents/Guardian' WHEN t.segment=2 THEN 'Instructor' ELSE 'Student Learner' END as segment_str,c.catename FROM ".TABLE_ASSET_TOPIC." t  LEFT JOIN ".TABLE_CATEGORY." c ON t.cateid=c.cateid WHERE t.is_deleted = 0 ";

			// Search
			if (!empty($key)) {
				$query_str.= " and ((t.topicname like '%".$key."%') OR (c.catename like '%".$key."%')   ) ";
			}
            if (!empty($cateid)) {
				$query_str.= " and  t.cateid='".$cateid."'";
			}

			$query_str.= " order by t.assettopicid asc ";

			// Pagination
			if (!empty($pn) and !empty($nr)) {
				// Navigation
    			$query_str.= " limit ".(($pn - 1) *  $nr).", ".$nr;
			}
            // echo $query_str;exit;
			$query = $conn->query($query_str);

			// Total records
			$rows_query = $conn->query("select FOUND_ROWS() as total_records");
			$rows_result = $rows_query->fetchAll(PDO::FETCH_OBJ);
			$total_records = $rows_result[0]->total_records;

			$arr['total_records'] = $total_records;
            $data_arr=$query->fetchAll(PDO::FETCH_OBJ);
        
            if(count($data_arr)>0)
            {
                require (dirname(__FILE__).'/awsfileserver.php'); 
                $s3=awsfileserver::connectS3();
                foreach($data_arr as $skey=>$res_val)
                {
                    $check_str = "SELECT * FROM ".TABLE_USER_COMPLETE_CONTENT." WHERE assettopicid = '".$res_val->assetcateid."' LIMIT 1";
                    $check_query = $conn->query($check_str);                    
                    $data_arr[$skey]->is_edit=($check_query->rowCount()>0)?"0":"1";
        
                    $image_url='';
                    if($res_val->image!='')
                    { 
                        $obj = new stdClass();
                        $obj->key_name=S3_TOPICS_URL.$res_val->image;			
                        $url=awsfileserver::getS3Url($s3,S3_BUCKET,$obj);	
                        $image_url=$url;
                    }
                    $data_arr[$skey]->image_url=$image_url;
                }
            }

			$arr['product'] = $data_arr;
			if(count($arr) != 0){
				//$conn->message(true, $pageData->successMsg[0], $arr);
                $conn->message(true,$conn->getMessage($lang,'product','success1'),$arr );
			}else{
				$conn->message(false,$conn->getMessage($lang,'product','error2'));
			}
		}
		else{
			$conn->message(false,$conn->getMessage($lang,'product','error1'));
		}
	}
	catch(PDOException $e){
		$conn->message(false,$conn->getMessage($lang,'product','error4'));
	}
}

// ADD PRODUCT
function addproduct () {
	global $conn;
	try {
        
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            
			$topicname = escape_str($_REQUEST["topicname"]);
			$cateid = escape_str($_REQUEST["cateid"]);
			$listorder = escape_str($_REQUEST["listorder"]);
            $parentid=0;
            $user_type =(isset($_REQUEST["user_type"]))?escape_str($_REQUEST["user_type"]):0;
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
            
            
            if(!($cateid!='' && $topicname!='' && $listorder!='' ) ){ $conn->message(false, 'FIELDS MISSING');exit; }               
        
			$status = 1;      
            //FILE UPLOAD
            if(isset($_FILES['file']) && $_FILES['file']['name'])
            {
                $obj = new stdClass();
                $obj->filekey = 'file';
                $obj->size = '10'; //IN MB
                $obj->type = array('jpg','jpeg','png');	
                $conn->validateFile($obj);			
                $obj->path = "../".S3_TOPICS_URL;
                $obj->filename = 'product_'.date('Ymd')."_".uniqid();			
                $image = $conn->uploadFile($obj);

                //S3 UPLOAD
                //S3 LIB
                require (dirname(__FILE__).'/awsfileserver.php'); 

                //S3 OBJ
                $s3=awsfileserver::connectS3();
                awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$image,dirname(__FILE__)."/../".S3_TOPICS_URL.$image);

                //DELETE AFTER MOVE TO S3
                @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$image);
            }else
            {
                $conn->message(false,$conn->getMessage($lang,'product','error3'));	
            }
        
            $insert = "INSERT INTO ".TABLE_ASSET_TOPIC." (`cateid`,`user_type`,segment ,  `parentid`, `topicname`, `image`, `position`, `listorder`, `status`, `is_deleted`, `created_on`, `modified_on`) VALUES ('".$cateid."','".$user_type."','".$segment."','".$parentid."','".$topicname."','".$image."','".$position."','".$listorder."','".$status."','0' , '".NOW."','".NOW."')"; 


           $insertquery = $conn->query($insert);
           $assettopicid = $conn->lastinsetid();
        
           $conn->message(true,$conn->getMessage($lang,'product','success1'),getProduct ($assettopicid));
        
		}else{
			$conn->message(false,$conn->getMessage($lang,'product','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'product','error4'));
	}
}

// UPDATE PRODUCT
function updateproduct () {
	global $conn;
	try {
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
		//$pageData = $conn->loadJSON($lang);
		if(isset($_SESSION["userid"])) {
            $assettopicid = escape_str($_REQUEST["assettopicid"]);
            
			$topicname = escape_str($_REQUEST["topicname"]);
			$cateid = escape_str($_REQUEST["cateid"]);
			$listorder = escape_str($_REQUEST["listorder"]);
            $parentid=0;
            $segment =(isset($_REQUEST["segment"]))?escape_str($_REQUEST["segment"]):0;
            
            if(!($assettopicid!='' && $topicname!='' && $cateid!='' && $listorder!='' ) ){ $conn->message(false, 'FIELDS MISSING');exit; }               
        
            $query_str = "SELECT assettopicid,image FROM ".TABLE_ASSET_TOPIC." WHERE assettopicid = '".$assettopicid."'  AND is_deleted='0' LIMIT 1";
            $query = $conn->query($query_str);
            $arr = $query->fetchAll(PDO::FETCH_OBJ);
        
            if(count($arr)== 1)
            {                
                $imagecond='';
                //FILE UPLOAD
                if(isset($_FILES['file']) && $_FILES['file']['name'])
                {
                    $obj = new stdClass();
                    $obj->filekey = 'file';
                    $obj->size = '10'; //IN MB
                    $obj->type = array('jpg','jpeg','png');	
                    $conn->validateFile($obj);			
                    $obj->path = "../".S3_TOPICS_URL;
                    $obj->filename = 'logo_'.date('Ymd')."_".uniqid();			
                    $image = $conn->uploadFile($obj);

                    //S3 UPLOAD
                    //S3 LIB
                    require (dirname(__FILE__).'/awsfileserver.php'); 

                    //S3 OBJ
                    $s3=awsfileserver::connectS3();
                    awsfileserver::checkupload($s3,S3_BUCKET,S3_TOPICS_URL.$image,dirname(__FILE__)."/../".S3_TOPICS_URL.$image);

                    //DELETE AFTER MOVE TO S3
                    @unlink(dirname(__FILE__).'/../'.S3_TOPICS_URL.$image);
                    
                    
                    $imagecond="`image`='".$image."',"; 
                    
                    if($arr[0]->image)
                    {
                        //DELETE OLD FILE
                        //awsfileserver::deleteobject($s3,S3_BUCKET,S3_TOPICS_URL.$arr[0]->image);
                    }
                }
        
                $update_str = "UPDATE ".TABLE_ASSET_TOPIC." SET  `cateid`='".$cateid."',segment='".$segment."',`topicname`='".$topicname."',".$imagecond."  `listorder`='".$listorder."',`modified_on`='".NOW."' WHERE assettopicid = '".$assettopicid."'";

                $conn->query($update_str);
                $conn->message(true,$conn->getMessage($lang,'product','success1'),getProduct ($assettopicid));
            }
            else
            {
                $conn->message(false,$conn->getMessage($lang,'product','error5'));
            }
        }else{
			$conn->message(false,$conn->getMessage($lang,'product','error1'));
		} 
	}
	catch(PDOException $e) {
		$conn->message(false,$conn->getMessage($lang,'product','error4'));
	}
}

// DELETE PRODUCT 
function deleteproduct () {
	global $conn;
	try{
		$lang = (isset($_REQUEST["lang"]))?$_REQUEST["lang"]:'en_us';	
        
		if(isset($_SESSION["userid"])){
			$assettopicid = escape_str($_REQUEST["assettopicid"]);
            
			$deletestr = "UPDATE ".TABLE_ASSET_TOPIC." SET `is_deleted` = '1' WHERE assettopicid = '".$assettopicid."'";
			$deletequery = $conn->query($deletestr);
			if($deletequery) {
				 $conn->message(true,$conn->getMessage($lang,'product','success1'));
			}
		}else{
			$conn->message(false,$conn->getMessage($lang,'product','error1'));
		}
	}catch(PDOException $e){
		echo $e->getMessage();
	}
}
// GET PRODUCT
function getProduct ($assettopicid)
{
	global $conn;
    $data_arr=array();
    if($assettopicid!='')
    {
        $data_arr=$conn->getQueryValue("SELECT t.*,c.catename FROM ".TABLE_ASSET_TOPIC." t  LEFT JOIN ".TABLE_CATEGORY." c ON t.cateid=c.cateid WHERE t.assettopicid = '".$assettopicid."' LIMIT 1");
        $data_arr=(count($data_arr)>0)?$data_arr[0]:array();
    }
    return $data_arr;
}

?>