<?php
  require '../conf/config.php';
  require './common.php';

  if( !$conn = new mysqli($host, $user, $pswd, $db)) {
    error_log("Connection failed.\n");
    exit;
  }
  
  (isset($_POST['chr'])) ? $chr=$_POST['chr'] : returnError("Error");
  (isset($_POST['sort_term'])) ? $sort_term=$_POST['sort_term'] : returnError("Error");
  (isset($_POST['prm_phenotype'])) ? $prm_phenotype=$_POST['prm_phenotype'] : returnError("Error");
  (isset($_POST['prm_effgrps'])) ? $prm_effgrps = $_POST['prm_effgrps'] : $prm_effgrps = array();
  (isset($_POST['start']) && is_numeric($_POST['start'])) ? $prm_start_entry_num = $_POST['start'] : returnError("Error");
  (isset($_POST['length']) && is_numeric($_POST['length'])) ? $prm_length = $_POST['length'] : returnError("Error");
  (isset($_POST['draw']) && is_numeric($_POST['draw'])) ? $prm_draw = $_POST['draw'] : returnError("Error");

  ##Varidating##
  _pregMatch($chr);
  _pregMatch($sort_term);
  _pregMatch($prm_phenotype);
  for($i=0;$i<count($prm_effgrps);$i++) {
	if(!(is_numeric($prm_effgrps[$i]))) {
		$errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid Value!!</font></div>";
                echo $errmsg;
                exit;
        };
  }
  if (!(is_numeric($prm_start_entry_num)) || !(is_numeric($prm_length)) || !(is_numeric($prm_draw))) {
 	$errmsg = "<div align=\"center\"><font color=\"red\" style=\"font-size:18px;\">Invalid Value!!</font></div>";
        echo $errmsg;
        exit;
  }

  $stmt = $conn->stmt_init();
  ##get effect information##
  $query = "select eff_name, eff_grp from sys_snpEff";
  $stmt->prepare($query);
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($row0, $row1);
  $data_array = array();
  while ($stmt->fetch()) {
        $eff_grp_map[$row0] = $row1;
  }

  ##make where eff_grp query##
  $where_effgrp = "";
/*
  if(count($prm_effgrps) > 0){
	$where_effgrp = " and exists(select id from id2eff i2e where i2e.eff_grp ";
        for ($i = 0; $i < count($prm_effgrps); $i++) {
                if($i == 0) {
                        $where_effgrp = $where_effgrp . "IN (?";
                } else {
                        $where_effgrp = $where_effgrp . ", ?";
                }
                if ($i == count($prm_effgrps)-1) {
                        $where_effgrp = $where_effgrp . ") and i2e.id=a.id)";
                }
        }
  } else if (count($prm_effgrps) == 0) {
			//$where_effgrp = " AND note IS NULL";
			$where_effgrp = "";
  }
*/
  if(count($prm_effgrps) > 0) {
         if (count($prm_effgrps) != 5) {
                if($prm_effgrps[0] != 6){
                        $where_effgrp = " and (exists(select id from id2eff i2e where i2e.eff_grp ";
                        for ($i = 0; $i < count($prm_effgrps); $i++) {
                                //if($i == 0 && $prm_effgrps[$i] != 6) {
                                if($i == 0) {
                                        $where_effgrp = $where_effgrp . "IN (?";
                                } else if ($prm_effgrps[$i] != 6) {
                                        $where_effgrp = $where_effgrp . ", ?";
                                }
                                if ($i == count($prm_effgrps)-1) {
                                        $where_effgrp = $where_effgrp . ") and i2e.id=a.id)";
                                }
                                if ($prm_effgrps[$i] == 6) {
                                        $where_effgrp = $where_effgrp . " OR note IS NULL";
                                        $slice = array_splice($prm_effgrps,$i,1);
                                }
                        }
                        $where_effgrp = $where_effgrp . ")";
                } else {
                        $where_effgrp = " and note IS NULL";
                        $slice = array_splice($prm_effgrps,0,1);
                }
        }
  }
  if ($chr != "all") {
        $where_effgrp = $where_effgrp." and chr = ?";
  }

  $sql_from_where_base = " sys_phenotype_gene a, sys_phenotype b where exists(select 1 from sys_chromosome c where c.id=a.chr) and a.phenotype_id = b.phenotype_id and b.phenotype = ? ";
  $query = "SELECT count(*) FROM". $sql_from_where_base. $where_effgrp;
  $stmt->prepare($query);
  if(count($prm_effgrps) > 0){
	if (count($prm_effgrps) != 5) {
		if ($chr == "all") {
  			$bind_param_array = array("s" . str_repeat("i", count($prm_effgrps)));
			$bind_param_array_2 = array_merge(array($prm_phenotype), $prm_effgrps);
		} else {
  			$bind_param_array = array("s" . str_repeat("i", count($prm_effgrps)) . "s");
  			$bind_param_array_2 = array_merge(array($prm_phenotype), $prm_effgrps,array($chr));
		}
  		for($i = 0; $i < count($bind_param_array_2); $i++){
  		      $bind_param_array[] = &$bind_param_array_2[$i];
  		}
 		call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
        } else {
		if ($chr == "all") {
                	$bind_param_array = array("s");
                	$bind_param_array_2 = array_merge(array($prm_phenotype));
		} else {
			$bind_param_array = array("ss");
                        $bind_param_array_2 = array_merge(array($prm_phenotype,$chr));
		}
                for($i = 0; $i < count($bind_param_array_2); $i++){
                       	$bind_param_array[] = &$bind_param_array_2[$i];
                }
                call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
        }
  } else {
        if ($chr == "all") {
                $bind_param_array = array("s");
                $bind_param_array_2 = array_merge(array($prm_phenotype));
        } else {
                $bind_param_array = array("ss");
                $bind_param_array_2 = array_merge(array($prm_phenotype,$chr));
        }
        for($i = 0; $i < count($bind_param_array_2); $i++){
                $bind_param_array[] = &$bind_param_array_2[$i];
        }
        call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
  }	
  $stmt->execute();
  $stmt->store_result();
  $records_total = 0;
  $stmt->bind_result($records_total);
  $stmt->fetch();

  $query = "SELECT chr, pos, prob, note, Effect FROM". $sql_from_where_base. $where_effgrp;
  if ($sort_term == "Probability") {
      $query .= " order by prob desc limit ?, ?";
//  	$query = "SELECT chr, pos, prob, note, Effect FROM sys_phenotype_gene a, sys_phenotype b where b.phenotype = ? and a.phenotype_id = b.phenotype_id".$where_effgrp." order by prob desc limit ?, ?";
  }else if ($sort_term == "Position") {
      $query .= " order by chr,pos limit ?, ?";
//  	$query = "SELECT chr, pos, prob, note, Effect FROM sys_phenotype_gene a, sys_phenotype b where b.phenotype = ? and a.phenotype_id = b.phenotype_id".$where_effgrp." order by chr,pos limit ?, ?";
  }
//error_log("Test:$query  $prm_phenotype, $prm_effgrps, $prm_start_entry_num, $prm_length");
  $stmt->prepare($query);
  if(count($prm_effgrps) > 0){
	if (count($prm_effgrps) != 5) {
		if ($chr == "all") {
  			$bind_param_array = array("s" . str_repeat("i", count($prm_effgrps))."ii");
  			$bind_param_array_2 = array_merge(array($prm_phenotype), $prm_effgrps, array($prm_start_entry_num, $prm_length));
		} else {
                	$bind_param_array = array("s" . str_repeat("i", count($prm_effgrps))."sii");
                	$bind_param_array_2 = array_merge(array($prm_phenotype), $prm_effgrps, array($chr,$prm_start_entry_num, $prm_length));
		}
  		for($i = 0; $i < count($bind_param_array_2); $i++){
        		$bind_param_array[] = &$bind_param_array_2[$i];
  		}
  		call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
        } else {
		if ($chr == "all") {
                	$bind_param_array = array("sii");
                	$bind_param_array_2 = array_merge(array($prm_phenotype), array($prm_start_entry_num, $prm_length));
		} else {
                	$bind_param_array = array("ssii");
                	$bind_param_array_2 = array_merge(array($prm_phenotype,$chr), array($prm_start_entry_num, $prm_length));
		}
                for($i = 0; $i < count($bind_param_array_2); $i++){
                        $bind_param_array[] = &$bind_param_array_2[$i];
                }
                call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
        }
  } else {
	if ($chr == "all") {
		$bind_param_array = array("sii");
		$bind_param_array_2 = array_merge(array($prm_phenotype), array($prm_start_entry_num, $prm_length));
	} else {
                $bind_param_array = array("ssii");
                $bind_param_array_2 = array_merge(array($prm_phenotype,$chr), array($prm_start_entry_num, $prm_length));
        }
        for($i = 0; $i < count($bind_param_array_2); $i++){
                $bind_param_array[] = &$bind_param_array_2[$i];
        }
        call_user_func_array(array($stmt, 'bind_param'), $bind_param_array);
  }
  $stmt->execute();
  $stmt->store_result();
  $stmt->bind_result($row0, $row1, $row2, $row3, $row4);
  $data_array = array();
  $count = -1;
  $check_pos = "";
  $check_pos_pre = "";
  $geneid = "";
  $name = "";
  $htmlstr = "";
  while ($stmt->fetch()) {
	$geneid = array();
  	$name = array();
	$genestr = "";
	$namestr = "";
	$effinfos = explode("---DIFFID---",$row4);
	$effinfos_cnt = count($effinfos);
	for ($i=0; $i<$effinfos_cnt; $i++) {
		$infos = explode("|",$effinfos[$i]);
		$names = explode(":",$infos[0]);
		if(count($infos) < 2) continue;
		//if (strcmp($names[0],"none")!=0 && strcmp($names[1],"none")!=0) {
			$impacts = explode(",",$infos[1]);
			$impacts_cnt = count($impacts);
			for ($j=0; $j<$impacts_cnt; $j++) {			
				$impact = $impacts[$j];
				//$impact = $infos[1];
				$imap = $impact;
				if($imap == "") continue;
				if (preg_match("/\+/",$impact)) {
                        	        $gtmp = explode("+",$impact);
                        	        $imap = $gtmp[0];
                        	}
                 		if (isset ($geneid[$eff_grp_map[$imap]])) {
                        		$geneid[$eff_grp_map[$imap]] .= "<br>".$names[0]."|".$impact;
                        	        $name[$eff_grp_map[$imap]] .= "<br>".$names[1]."|".$impact;
                       		} else {
                        	        $geneid[$eff_grp_map[$imap]] = $names[0]."|".$impact;
                        	        $name[$eff_grp_map[$imap]] = $names[1]."|".$impact;
                        	}
			}
		//}
	}

	$htmlstr = "";
        $clrarr = array(
        		"0" => "#00BFFF",
               		"1" => "#FFFF00",
                	"2" => "#EE9A00",
                        "3" => "#8B0000"
                        );
	krsort($geneid);
	foreach ($geneid as $key => $value) {
		$nimpact = $key;
		$geneids = explode("<br>",$geneid[$nimpact]);
		$names = explode("<br>",$name[$nimpact]);
//		$geneids = split("<br>",$geneid[$nimpact]);
//		$names = split("<br>",$name[$nimpact]);
		$count = count($geneids);
		for ($i=0;$i<$count;$i++) {
			if(strcmp($genestr,"")!=0) {
				$ginfo = $geneids[$i];
				$ninfo = $names[$i];
				$ginfos = explode("|",$ginfo);
				$ninfos = explode("|",$ninfo);
//				$ginfos = split("\|",$ginfo);
//				$ninfos = split("\|",$ninfo);
				if(strcmp($ginfos[0],"")!=0) {
					$genestr .= "<br>".$ginfos[0];
				} else {
					$genestr .= "<br>&nbsp;";
				}
				if(strcmp($ginfos[0],"")!=0) {
                                        $namestr .= "<br>".$ninfos[0];
                                } else {
                                        $namestr .= "<br>&nbsp;";
                                }
				$gcolor = $ginfos[1];
				//for ($i = 0; $i < $count; $i++) {
				if (preg_match("/\+/",$gcolor)) {
					$gtmp = explode("+",$gcolor);
					$gcolor = $gtmp[0];
				}
				$htmlstr .= "<div id=\"effbox\" style=\"background-color:".$clrarr[$eff_grp_map[$gcolor]].";width:10px;height:15px;display:inline-block;\">&nbsp;&nbsp;&nbsp;&nbsp;$ginfos[1]</div><br>";
//				$htmlstr = $htmlstr."<div id=\"effbox\" style=\"background-color:".$clrarr[$eff_grp_map[$gcolor]].";width:10px;height:15px;display:inline-block;\">&nbsp;&nbsp;&nbsp;&nbsp;$ginfos[1]</div><br>";
				//}
			} else {
				$ginfo = $geneids[$i];
                                $ninfo = $names[$i];
				$ginfos = explode("|",$ginfo);
				$ninfos = explode("|",$ninfo);
//                                $ginfos = split("\|",$ginfo);
//                                $ninfos = split("\|",$ninfo);
                                $genestr = $ginfos[0];
                                $namestr = $ninfos[0];
				if(strcmp($ginfos[0],"")!=0) {
                                        $genestr = $ginfos[0];
                                } else {
                                        $genestr = "&nbsp;";
                                }
                                if(strcmp($ginfos[0],"")!=0) {
                                        $namestr = $ninfos[0];
                                } else {
                                        $namestr = "&nbsp;";
                                }
				$gcolor = $ginfos[1];
				if (preg_match("/\+/",$gcolor)) {
                                        $gtmp = explode("+",$gcolor);
                                        $gcolor = $gtmp[0];
                                }
				$bgcolor = "transparent";
				if(array_key_exists($gcolor, $eff_grp_map) && array_key_exists($eff_grp_map[$gcolor], $clrarr)) $bgcolor = $clrarr[$eff_grp_map[$gcolor]];
				$htmlstr .= "<div id=\"effbox\" style=\"background-color:". $bgcolor. ";width:10px;height:15px;display:inline-block;\">&nbsp;&nbsp;&nbsp;&nbsp;$ginfos[1]</div><br>";
			}
		}
	}
	$probability = round($row2,4);
	$position = number_format($row1);
// 	array_push($data_array, array("<div align=\"center\">$row0</div>", "<div align=\"center\"><a href=\"javascript:_moveVarpos('$row0|$row1');\"title=Move this position.\">$position</a></div>", "<div align=\"center\">$probability</div>", "<span class=\"GeneID\">$genestr</span>", "<span class=\"Name\">$namestr</span>", $htmlstr));
	array_push($data_array, array($row0, $row1, $position, $probability, $genestr, $namestr, $htmlstr));
  }

  echo json_encode(
  		array(
  				"draw" => (int)$prm_draw,
  				"recordsTotal" => $records_total,
  				"recordsFiltered" => $records_total,
  				"data" => $data_array,
  		)
  );
function returnError($str){
    echo $str;
}
?>
